<!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>
body {
position: relative;
}
#box {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100vh;
background-color: grey;
cursor: pointer;
}
</style>
</head>
<body>
<div id="box">
</div>
<script>
function DragHooks() {
let box = document.querySelector("div")
box.addEventListener('mousedown', function (e) {
var firstX = e.clientX;//获得鼠标点击的位置
var firstY = e.clientY;
var nowX = box.offsetLeft;//获得div即移动方块的初始位置
var nowY = box.offsetTop;
document.onmousemove = function (e) {
//更改元素的位置:初始的位置 +鼠标的位置-鼠标在元素内的位置
box.style.left = nowX + e.clientX - firstX + 'px';
box.style.top = nowY + e.clientY - firstY + 'px';
console.log('onmousemove', box.style.left, nowX, e.clientX, firstX)
}
})
//当鼠标按键放开的时候 将鼠标移动事件置为空
box.addEventListener('mouseup', function () {
document.onmousemove = null
})
}
DragHooks()
</script>
</body>
</html>
JavaScript实现-拖拽
猜你喜欢
转载自blog.csdn.net/weixin_56356934/article/details/140750417
今日推荐
周排行