要点:
1.这个例子中,如果可以直接pageX或者pageY就可以直接写一步操作即可,因为IE8不支持,通过 pageX (页面的具体横坐标位置)= scrollLeft(卷曲的横坐标距离) + clientX(可视区域横轴距离)这样曲线兼容 。
2.在JS高级里面,有window.event来获取函数对象,而在谷歌火狐直接可以通过传参返回,以后再详细说明。
3.这个例子中,是通过对象内部调用另外一个对象的方法实现的,注意理解。
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
body{
height: 1800px;
}
img{
position: absolute;
width: 250px;
height: auto;
}
</style>
</head>
<body>
<img src="images23/zhuqiu.gif" id="zhuqiu">
<script type="text/javascript">
function myGet(id){
return document.getElementById(id);
}
var evt = {
getEvent:function(evt){
return window.event || evt;
},
// 兼容IE浏览器不支持.evt的事件
getClientX:function(evt){
return this.getEvent(evt).clientX;
},
// 可视区域横坐标
getClientY:function(evt){
return this.getEvent(evt).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;
},
//兼容向右卷曲的距离
getPageX:function (evt){
return this.getEvent(evt).pageX ? this.getEvent(evt).pageX
: this.getClientX(evt) + this.getScrollLeft();
},
// 鼠标的位置用的是pageX或者pageY属性,但是IE8不兼容这个属性,只能通过卷曲距离 + 可视距离曲线兼容
getPageY:function(evt){
return this.getEvent(evt).pageY ? this.getEvent(evt).pageY
: this.getClientY(evt) + this.getScrollTop();
}
}
document.onmousemove=function (e) {
myGet("zhuqiu").style.left=evt.getPageX(e)+"px";
myGet("zhuqiu").style.top=evt.getPageY(e)+"px";
};
</script>
</body>
</html>
效果: