一、 实验想法
当我的鼠标按下去之后他就跟着鼠标移动,当我鼠标抬起时他就停止运动
二、实验思路
- 创建一个好看的移动物体(这里是一个方块代替)
- 知道鼠标点下去的坐标(作用在方块上的坐标)
- 获取方块的相对位置
- 获取方块的宽高
- 鼠标点下去时始终让鼠标在方块的中心位置(这里不然获取的一直是方块左上方的坐标)
三、实验步骤
当鼠标按下去时打印鼠标的相对位置
<style>
div{
width: 100px;
height: 100px;
background-color: peru;
}
</style>
</head>
<body>
<div></div>
<script>
let div = document.querySelector("div")
div.onmousedown = function(event){ //鼠标按下起
div.onmousemove = function(ev){ //鼠标移动时
console.log(ev.offsetX)
console.log(ev.offsetY)
}
}
</script>
</body>
</html>
鼠标位置的打印
结束鼠标的位置,不然一直跟着鼠标跑
div.onmouseup = function() { //鼠标抬起时停止移动
div.onmousemove = null
}
让盒子知道鼠标的位置
div.style.position = "absolute"//相对鼠标时盒子需要绝对定位(鼠标在哪盒子在哪)
w = parseInt(getComputedStyle(div).width) //获取盒子的宽
h = parseInt(getComputedStyle(div).height) //获取盒子的高
div.style.left = (ev.pageX - w / 2 ) + "px" //鼠标的位置
div.style.top = (ev.pageY - h / 2 ) + "px"
成品代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
div {
width: 100px;
height: 100px;
background-color: peru;
}
</style>
</head>
<body>
<div></div>
<script>
let div = document.querySelector("div")
div.style.position = "absolute" //相对鼠标时绝对定位(鼠标在哪盒子在哪)
w = parseInt(getComputedStyle(div).width) //获取盒子的宽
h = parseInt(getComputedStyle(div).height) //获取盒子的高
div.onmousedown = function(event) { //鼠标按下起
div.onmousemove = function(ev) { //鼠标移动时
console.log(ev.offsetX)
console.log(ev.offsetY)
div.style.left = (ev.pageX - w / 2 ) + "px" //鼠标的位置
div.style.top = (ev.pageY - h / 2 ) + "px"
}
}
div.onmouseup = function() { //鼠标抬起时停止移动
div.onmousemove = null
}
</script>
</body>
</html>
四、效果展示
初始位置
被点击之后跟随鼠标移动的位置