<style>
#dd {
width: 100px;
height: 100px;
background: black;
position: absolute;
}
</style>
<div id="dd"></div>
<script>
let dd = document.querySelector('#dd');
let isMove = false; //是否可以移动
function move(x, y) {
if (isMove) {
dd.style.left = x - dd.clientWidth / 2 + 'px';
dd.style.top = y - dd.clientHeight / 2 + 'px'
}
}
/*鼠标按下时可以移动*/
dd.addEventListener('mousedown', function () {
isMove = true;
})
/*鼠标抬起后不可移动*/
dd.addEventListener('mouseup', function () {
isMove = false;
})
/*根据鼠标位置定位*/
document.body.addEventListener('mousemove', function (e) {
move(e.clientX, e.clientY);
})
</script>
JavaScript 鼠标拖拽
最新推荐文章于 2024-10-04 10:08:54 发布