此外,通过鼠标在网页上的点击,我们还可以获得许多有用的参数,如获得当前鼠标的坐标。我们根据其参照物的不同,以下几套坐标系。一套是以当前浏览器的可视区为参照物(clientX, clientY),另一套是以显示器的屏幕为参照物(screenX, screenY)。此外微软还有一套坐标系(x,y),它是相对于触发事件的对象的offsetParent的,火狐有另一套坐标系(pageX, pageY),它是相对于当前网页的。我们可以通过如下函数来获得鼠标在网页的坐标。
var getCoordInDocument = function(e) {
e = e || window.event;
var x = e.pageX || (e.clientX +
(document.documentElement.scrollLeft
|| document.body.scrollLeft));
var y= e.pageY || (e.clientY +
(document.documentElement.scrollTop
|| document.body.scrollTop));
return {'x':x,'y':y};
}
<script type="text/javascript">
var getCoordInDocumentExample = function(){
var coords = document.getElementById("coords");
coords.onmousemove = function(e){
var pointer = getCoordInDocument(e);
var coord = document.getElementById("coord");
coord.innerHTML = "X,Y=("+pointer.x+", "+pointer.y+")";
}
}
var getCoordInDocument = function(e) {
e = e || window.event;
var x = e.pageX || (e.clientX +
(document.documentElement.scrollLeft
|| document.body.scrollLeft));
var y= e.pageY || (e.clientY +
(document.documentElement.scrollTop
|| document.body.scrollTop));
return {'x':x,'y':y};
}
window.onload = function(){
getCoordInDocumentExample();
};
</script>
<div id="coords" style="width:500px;height:200px;background:#F2F1D7;border:2px solid #336699;">
请在这里移动鼠标。
</div>
<br />
<div id="coord" style="width:500px;border:2px solid #336699;"> </div>
至于mouseover,mousemove,mouseout没有什么好说,并且无浏览器差异。我们来看鼠标滚轮事件,这个差异很严重。IE、Safari、 Opera 、chrome是mousewheel事件,Firefox是DOMMouseScroll事件。事件属性方面,IE等是event. wheelDelta,Firefox是event. detail。IE等往上滚一圈为120,往下滚一圈为-120。Firefox往上滚一圈为-3,往下滚一圈为3。我们可以构造一个函数来削除它们的差异。
var mouseScroll = function(fn){
var roll = function(){
var delta = 0,
e = arguments[0] || window.event;
delta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
fn(delta);//回调函数中的回调函数
}
if(/a/[-1]=='a'){
document.addEventListener('DOMMouseScroll', roll, false);
}else{
document.onmousewheel = roll;
}
}
此函数接受一函数作为参数,如:
mouseScroll(function(delta){
var obj = document.getElementById('scroll'),
current = parseInt(obj.offsetTop)+(delta*10);
obj.style.top = current+"px";
});
<script type="text/javascript">
var $ = function(id){ return document.getElementById(id)}
window.onload = function(){
mouseScroll(function(delta){
var obj = $('scroll'),
current = parseInt(obj.offsetTop)+(delta*10);
obj.style.top = current+"px";
});
}
var mouseScroll = function(fn){
var roll = function(){
var delta = 0,
e = arguments[0] || window.event;
delta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
fn(delta);//回调函数中的回调函数
}
if(/a/[-1]=='a'){
document.addEventListener('DOMMouseScroll', roll, false);
}else{
document.onmousewheel = roll;
}
}
</script>
<style title="text/css">
#scroll {
color:#fff;
background:#369;
width:70px;
height:70px;
position:absolute;
left:500px;
top:200px;
}
</style>
<div id="scroll">能用鼠标移动的方块</div>