案例介绍
1、鼠标不断移动,使用鼠标移动事件:mousemove
2、在页面中移动,给document注册事件
3、图片要移动距离,而且不占位置,我们使用绝对定位即可
4、核心原理:每次鼠标移动,我们都会获得最新的鼠标坐标,把这个x和y坐标作为图片的top和left值就可以移动图片
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
img {
top: 5px;
left: 5px;
position: absolute;
}
</style>
</head>
<body>
<img src="images/angel.gif" alt="">
<script>
// 1、mousemove只要鼠标移动1px 就会触发这个事件
var pic = document.querySelector('img');
document.addEventListener('mousemove', function(e) {
var x = e.pageX;
var y = e.pageY;
console.log(x);
// 减数是为了让图片居中对齐
pic.style.left = x - 45 + 'px';
pic.style.top = y - 35 + 'px';
})
</script>
</body>
</html>