图片跟随鼠标效果实现步骤详解(源码分享)

演示效果GIF动画:

图片跟随鼠标效果
图片跟随鼠标效果

图片跟随鼠标效果实现步骤:

1、图片绝对定位,通过修改left和top属性,来移动图片
#img{position: absolute; left: 0; top: 0;}

2、获取图片对象
var img = document.getElementById(‘img’);

3、文档的鼠标移动事件,执行函数
document.onmousemove = function(e){执行代码}

4、代码部分为修改图片的属性
img.style.left = e.clientX + ‘px’;
img.style.top = e.clientY + ‘px’;

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#img{position: absolute; left: 0; top: 0; border:1px solid #ccc;}

<img id="img" src="./123.jpg" alt="" width="200" />
<div>X:<span id="xitem">横坐标</span> / Y:<span id="yitem">纵坐标</span></div>
//script代码开始
var img = document.getElementById('img');
var x = document.getElementById('xitem');
var y = document.getElementById('yitem');

document.onmousemove = function(e)
{
img.style.left = e.clientX + 'px';
img.style.top = e.clientY + 'px';

x.innerHTML = e.clientX;
y.innerHTML = e.clientY;
}
//script代码结束

完整源码见:https://github.com/webjust/case-study/tree/master/Javascript/001