<!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>
鼠标按下盒子跟随鼠标移动,鼠标松开,盒子停止移动
最新推荐文章于 2024-09-11 09:30:30 发布
本文介绍了如何使用HTML、CSS和JavaScript为一个红色正方形创建一个简单的鼠标拖拽效果,当鼠标按下并移动时,盒子会跟随鼠标位置移动。
528

被折叠的 条评论
为什么被折叠?



