这个案例是当你的鼠标按压下去后,div跟着你的鼠标移动而移动,当你的鼠标抬起后,div不随着鼠标移动而移动。类似于电脑移动应用图标的感觉。
代码
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>div移动</title><style>*{margin: 0;padding: 0;}div{width: 100px;height: 100px;background-color: aqua;position: absolute;}</style>
</head>
<body><div></div><script>let div1 = document.querySelector('div')w = parseInt(getComputedStyle(div1).width)h = parseInt(getComputedStyle(div1).height)div1.onmousedown = function(event){div1.onmousemove = function(event1){div1.style.left = (event1.pageX-w/2) + 'px'div1.style.top = (event1.pageY-h/2) + 'px'}}div1.onmouseup = function(){// 解除DOM0事件绑定div1.onmousemove = nulldiv1.onmousedown = null}</script>
</body>
</html>
结果
不嫌弃的点点关注,点点赞 ଘ(੭ˊᵕˋ)੭* ੈ✩‧