下文兼容性封装了滚动距离函数,client函数,page函数。
var evt = {
//兼容事件处理函数对象 作用是当需要e参数时,首先调用该方法返回适用于自身游览器的参数(e或者window.event)
getEvent: function(e) {
return e || window.event;
},
//兼容x轴浏览器滚动距离
getScrollX: function() {
return window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
},
//兼容y轴浏览器滚动距离
getScrollY: function() {
return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
},
//兼容clientX
getClientX: function(e) {
return this.getEvent(e).clientX;
},
//兼容clientY
getClientY: function(e) {
return this.getEvent(e).clientY;
},
//兼容pageX
getPageX: function(e) {
return this.getEvent().pageX ? this.getEvent().pageX : this.getClientX() + this.getScrollX();
},
//兼容pageY
getPageY: function(e) {
return this.getEvent().pageY ? this.getEvent().pageY : this.getClientY() + this.getScrollY();
}
};
下面在Body中加入一个小鸟图片,id为bird。进行关于鼠标跟随事件的兼容性函数测试。
var bird = document.getElementById('bird');
//鼠标移动事件
document.onmousemove = function(e) {
//client 可视区域坐标
// bird.style.left = e.clientX+'px';
// bird.style.top = e.clientY+'px';
//page 是页面的坐标,ie低版本没有e参数,所有无法调用page
//bird.style.left = e.pageX+'px';
//bird.style.top = e.pageY+'px';
//所以在兼容性设置中使用window.event.clientX,但是鼠标向下滚动会导致目标丢失,由于垂直滚动的距离不在可视化Y内计数
// bird.style.left = window.event.clientX+'px';
// bird.style.top = window.event.clientY+'px';
//所以我们人为构造,可视区域的坐标+垂直滚动的距离=page
// bird.style.left = window.event.clientX + getScroll().leftW + 'px';
// bird.style.top = window.event.clientY + getScroll().topW + 'px';
//兼容性函数测试
bird.style.left = evt.getPageX()+'px';
bird.style.top = evt.getPageY() + 'px';
}