老生常谈的东西了,直
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拖拽</title>
<style>
.box {
position: absolute;
width: 100px;
height: 100px;
background: red;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
let box = document.querySelector(".box");
//鼠标按下
box.onmousedown = function () {
//这里注意一下不要写成box.onmousemove
window.onmousemove = function (e) {
box.style.left = e.clientX - 50 + "px";
box.style.top = e.clientY - 50 + "px";
}
}
//鼠标松开,取消鼠标移动事件
box.onmouseup = function(){
window.onmousemove = null;
}
</script>
</body>
</html>
接上代码