鼠标按住方块,可拖动,松开方块不能被拖动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 200px;
height: 200px;
background-color: orangered;
position: fixed;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
var box = document.getElementById('box');
box.onmousedown=function (e) {
//鼠标和元素左上右上
var offsetX = e.offsetX;
var offsetY = e.offsetY;
//添加onmousemove
document.onmousemove=function (e) {
e=e||window.event;
//视口
var clientX = e.clientX;
var clientY = e.clientY;
box.style.top=(clientY-offsetY)+'px'
box.style.left=(clientX-offsetX)+'px'
}
};
box.onmouseup=function () {
//鼠标松开,停
document.onmousemove=null;
}
</script>
</body>
</html>