这个是案例图:
案例分析:
(1)、鼠标不断的移动,使用鼠标移动事件:mousemove
(2)、在页面中移动,给document注册事件
(3)、图片要移动距离,而且不占位置,我们使用绝对定位即可
(4)、核心原理:每次鼠标移动,我们都会获得最新的鼠标坐标,把这个X和Y坐标作为图片的top和left 值就可以移动图片
<!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>
<style>
img {
position: absolute;
top: 2px;
}
</style>
</head>
<body>
<img src="../images/ange1.gif" alt="">
<script>
var pic = document.querySelector('img');
document.addEventListener('mousemove', function(e) {
// 1. mousemove 只要我们鼠标移动1px 就会触发这个事件
// console.log(1);
// 2. 核心原理:每次鼠标移动,我们都会获得最新的鼠标坐标,把这个X和Y坐标作为图片的top和left 值就可以移动图片
var x = e.pageX;
var y = e.pageY;
console.log('x坐标是' + x, 'y坐标是' + y);
// 3. 千万不要忘记给 left 和 top 添加 px 单位
pic.style.left = x - 120 + 'px';
pic.style.top = y - 120 + 'px';
})
</script>
</body>
</html>