目标效果
代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
img {
/* 为鼠标图片开启绝对定位,不占用文档流位置 */
position: absolute;
}
</style>
<body>
<img src="./angel.gif" alt="">
<script>
var myImg = document.querySelector('img');
// 为document添加mousemove事件
document.addEventListener('mousemove', function (e) {
// 改变图片的top和left值,使其与pageY和pageX相等
// pageX和pageY不带单位,需要用字符串补上
myImg.style.top = e.pageY + 'px';
myImg.style.left = e.pageX + 'px';
});
</script>
</body>
</html>