概述
<!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>Document</title>
</head>
<body>
<div class="box">
</div>
</body>
</html>
<style>
.box {
width: 200px;
height: 200px;
background-color: red;
position: absolute;
top: 0;
left: 0;
}
</style>
<script>
var box = document.querySelector(".box")
box.addEventListener('mousedown', function (e) {
var x = e.pageX - box.offsetLeft // 鼠标距离页面位置 - 盒子距离左边的位置 = 鼠标点击位置到盒子边缘的距离
var y = e.pageY - box.offsetTop
document.addEventListener('mousemove',moveS)
function moveS(e) {
box.style.left = e.pageX - x + 'px' //鼠标所在位置 - 鼠标到盒子边缘的距离 = 盒子距离左边的距离
box.style.top = e.pageY - y + 'px'
}
document.addEventListener('mouseup',function (e) {
document.removeEventListener('mousemove',moveS)
})
})
</script>
最后
以上就是苗条烧鹅为你收集整理的鼠标按下盒子跟随鼠标移动,鼠标松开,盒子停止移动的全部内容,希望文章能够帮你解决鼠标按下盒子跟随鼠标移动,鼠标松开,盒子停止移动所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复