实现一个可以拖动的DIV。
<div class= "xxx"></div>
var dragging = false var position = null xxx.addEventListener('mousedown',function(e){ dragging = true position = [e.clientX, e.clientY] }) document.addEventListener('mousemove', function(e){ if(dragging === false) return null const x = e.clientX const y = e.clientY const deltaX = x - position[0] const deltaY = y - position[1] const left = parseInt(xxx.style.left || 0) const top = parseInt(xxx.style.top || 0) xxx.style.left = left + deltaX + 'px' xxx.style.top = top + deltaY + 'px' position = [x, y] }) document.addEventListener('mouseup', function(e){ dragging = false })
修改之后加上了注释。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.xxx{
width: 100px;
height: 100px;
background: red;
left: 20px;
top: 20px;
position: relative;
}
</style>
</head>
<body>
<div class="xxx"></div>
<script>
var dragging = false; //拖拽的状态
var position = null; //当前的定位
var xxx = document.querySelector(".xxx");
// console.log(xxx)
xxx.addEventListener('mousedown',function(e){ //创建事件监听
// console.log(1)
dragging = true; //拖拽状态
position = [e.clientX,e.clientY]; //记录当前位置
})
// 移动的设置
xxx.addEventListener('mousemove',function(e){
// console.log(1)
if(dragging === false) return null; //判断状态,如果为false返回空
const x=e.clientX; // 设置原位置坐标
const y=e.clientY;
const deltaX = x -position[0]; // 设置拖拽后位置的距离
const deltaY = y - position[1];
const left = parseInt(xxx.style.left || 0); //设置初始为值
const top = parseInt(xxx.style.top || 0);
xxx.style.left = left + deltaX +'px'; //设置坐标位置
xxx.style.top = top + deltaY +'px';
position = [x,y]; //重新定位
})
xxx.addEventListener('mouseup',function(e){
// console.log(1)
dragging = false; //鼠标抬起,改变状态
})
</script>
</body>
</html>

浙公网安备 33010602011771号