拖拽练习
- 通过事件监听来实现拖拽效果
- 把垃圾文件丢进垃圾桶
@_@
- 代码演示
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.file {
position: absolute;
left: 300px;
top: 300px;
width: 100px;
height: 100px;
background-color: pink;
}
.trash-can {
width: 150px;
height: 200px;
background-color: grey;
font-size: 22px;
}
</style>
</head>
<body>
<div class="file">垃圾文件</div>
<div class="trash-can">垃圾桶</div>
<script>
const file = document.querySelector('.file')
const trashCan = document.querySelector('.trash-can')
file.addEventListener('mousedown', (e) => {
//按下时获取此时相对鼠标的偏移量
let remainLeft = e.pageX - file.offsetLeft
let remainTop = e.pageY - file.offsetTop
//监听鼠标移动以及松开
window.addEventListener('mousemove', a)
file.addEventListener('mouseup', b)
function a(e) {
file.style.left = e.pageX - remainLeft + 'px'
file.style.top = e.pageY - remainTop + 'px'
}
function b(e) {
if (parseFloat(file.style.left) <= 150 && parseFloat(file.style.top) <= 200) {
file.parentNode.removeChild(file)
} else {
file.style.left = e.pageX - remainLeft + 'px'
file.style.top = e.pageY - remainTop + 'px'
}
//清除监听
window.removeEventListener('mousemove', a)
file.removeEventListener('mouseup', b)
}
//清除默认样式
e.preventDefault()
})
/* 由此小案例来加深知识点:
* 通过addEventListener监听的事件及其回调函数只能被removeEventListener清除
* removeEventListener(enent, fn) 俩参数是必须传的
* 执行的回调函数fn不能是匿名函数,否则清除无效
*/
</script>