跟随鼠标的案例
<!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>
img {
position: absolute;
width: 150px;
}
</style>
</head>
<body>
<img src="001.jpg" alt="">
<script>
var pic = document.querySelector('img');
document.addEventListener('mousemove',function(e){
//1.mousemove 只要我们鼠标移动1px 就会触发这个事件
//2.核心原理:每次鼠标移动,我们都会获得最新的鼠标坐标,把这个x和y坐标作为图片的top和left 值 就可以移动图片
var x = e.pageX;
var y = e.pageY;
//3.别忘了拼接一个px
pic.style.left = x-75 + 'px';
pic.style.top = y-25 + 'px';
})
</script>
</body>
</html>
就是通过获取 pageX pageY 来实时修改图片的left top 注意:定位为absolute