效果图:
代码:
<!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>
<style>
div {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0px;
top: 0px;
}
</style>
</head>
<body>
<h2>鼠标绑定小盒子</h2>
<div id="div"></div>
</body>
<script>
// 1.获取鼠标的X,y坐标
// 给div进行赋值
let div=document.getElementById('div')
document.onmousemove=function(e){
let event=e || window.event
div.style.left=event.clientX-div.clientWidth/2+'px'
div.style.top=event.clientY-div.clientHeight/2+'PX'
}
</script>
</html>
代码逻辑分析;
通过事件对象来获取鼠标移动的坐标,然后进行赋值。
div.style.left=event.clientX-div.clientWidth/2+'px'
div.style.top=event.clientY-div.clientHeight/2+'PX'