<!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>跟随鼠标的天使</title>
</head>
<style>
img{
position: absolute;
transform: translate(-50%,-50%);
/*默认是图片的左上角跟着鼠标移动,添加了transform: translate(-50%,-50%),就会
让top和left分别反转自身的50%这样就会让鼠标在图片的中间了*/
}
</style>
<body>
<img src="D:/vscode/vs/image/天使.png" alt="">
<script>
//让天使的图片一直跟着鼠标进行移动
//1)鼠标不断的移动,使用鼠标移动事件:mousemove
//2)在页面中移动,所以给document注册事件
//3)图片要移动距离,而且不占位置,所以使用绝对定位即可
//4)核心原理:每次鼠标移动,我们就会获得鼠标的最新的坐标,把这个x和y坐标作为图片的top和left值就可以移动图片
let pic=document.querySelector('img');
document.addEventListener('mousemove',function(e){
//1.mousemove只要我们鼠标移动1px,就会触发这个事件
//console.log(1);
let x=e.pageX;
let y=e.pageY;
//千万不要忘记给top和left添加单位
pic.style.left=x+'px';
pic.style.top=y+'px';
})
</script>
</body>
</html>
注意:document.addEventListener
这里不要写成pic.addEventListener
,即不要给图片绑定鼠标移动事件,如果给图片绑定了只有鼠标在图片上移动了才会让图片跟随鼠标。