图片跟随鼠标移动效果实现

html代码

1
<img src="1.jpg" alt="" id="img" />

css代码

1
2
3
4
5
6
7
8
9
10
*{
margin: 0;
padding: 0;
}
body{
height: 2000px;
}
img{
position: absolute;
}

JavaScript代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var move = {
// window.event和事件参数对象e的兼容
getEvent: function (event) {
return window.event || event;
},
// 可视区域的横坐标的兼容代码
getClientX: function (event) {
return this.getEvent(event).clientX;
},
// 可视区域的纵坐标的兼容代码
getClientY: function (event) {
return this.getEvent(event).clientY;
},
// 页面向左卷曲出去的横坐标
getScrollLeft: function () {
return window.pageXOffset || document.body.scrollLeft
|| document.documentElement.scrollLeft || 0;
},
// 页面向上卷曲出去的纵坐标
getScrollTop: function () {
return window.pageYOffset || document.body.scrollTop
|| document.documentElement.scrollTop || 0;
},
// 相对于页面的横坐标(pageX或者是clientX + scrollLeft)
getPageX: function (event) {
return this.getEvent(event).pageX ? this.getEvent(event).pageX:
this.getClientX(event) + this.getScrollLeft();
},
// 相对于页面的纵坐标(pageY或者是clientY + scrollTop)
getPageY: function (event) {
return this.getEvent(event).pageY ? this.getEvent(event).pageY:
this.getClientY(event) + this.getScrollTop();
}
};

document.onmousemove = function (event) {
document.getElementById("img").style.left = move.getPageX(event)+"px";
document.getElementById("img").style.top = move.getPageY(event)+"px";
};