<style>
#box{
width: 100px;
height: 100px;
background-color: bisque;
border-radius: 50%;
position: absolute;
}
</style>
<body>
<div id="box" style="left:100px; top:100px"></div>
<div id="box2"></div>
<script>
{
let box = document.querySelector("#box");
let starMouse = {};
let startEl = {};
// console.log(getComputedStyle(box));
//获取和设置 元素移动的值
function css(el,attr,val){
//获取元素的值
if(val === undefined){
//getComputedStyle(el): 会返回指定元素的所有style, 返回值是对象类型
return parseFloat(getComputedStyle(el)[attr]);
}
//设置元素的值
el.style[attr] = val + "px";
}
let move = (e)=>{
// 鼠标移动后的位置
let newMouse = {
x:e.clientX,
y:e.clientY
}
// 鼠标移动的距离= 鼠标移动后的位置-鼠标去移动前的位置
let disMouse = {
x: newMouse.x - starMouse.x,
y: newMouse.y - starMouse.y
}
css(box,"left",startEl.x + disMouse.x);
css(box,"top",startEl.y + disMouse.y);
// box.style.left = (startEl.x + disMouse.x) + "px";
// box.style.top = (startEl.y + disMouse.y) + "px";
}
box.addEventListener("mousedown",(e)=>{
// console.log(e);
// 鼠标每次按下的时候,只是重新赋值,而不是重新申请空间
starMouse = {
x: e.clientX,
y: e.clientY
}
// console.log(starMouse);
startEl = {
x: css(box,"left"),
y: css(box,"top")
}
// console.log(startEl);
document.addEventListener("mousemove",move);
document.addEventListener("mouseup",()=>{
document.removeEventListener("mousemove",move);
});
});
}
</script>
</body>
来源:CSDN
作者:weixin_46174967
链接:https://blog.csdn.net/weixin_46174967/article/details/104135966