当鼠标按下时拖动元素,简单的JS实现
- JS笔记
- 2021-07-28
- 1075热度
- 0评论
记录
监听需要移动元素的键盘按下、松开事件和文档对象的鼠标移动事件,
通过一个布尔值作为是否移动的标志,按下时为TRUE,代表跟随移动,鼠标松开为FALSE,代表不跟随移动,鼠标移动时改变元素偏移量。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>物体跟着鼠标移动</title>
</head>
<style>
.box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0;
top: 0;
}
</style>
<body>
<div class="box"></div>
</body>
<script>
var boxDom = document.querySelector(".box");
var flag=false,offX,offY;
boxDom.onmousedown=function (){
let evt = event || window.event;
offX=evt.clientX-window.getComputedStyle(boxDom,null)["left"].slice(0,-2);
offY=evt.clientY-window.getComputedStyle(boxDom,null)["top"].slice(0,-2);
flag=true;
}
boxDom.onmouseup=function (){
flag=false;
}
document.onmousemove = function (event) {
if(flag){
let evt = event || window.event;
console.log(evt.clientX -offX);
console.log(evt.clientY - offY);
boxDom.style.left = evt.clientX -offX + "px";
boxDom.style.top = evt.clientY - offY + "px";
}
}
</script>
</html>