js取鼠标坐标位置
取鼠标坐标位置有这些:鼠标在视口的坐标位置(clientX,clientY),鼠标在页面的坐标位置(pageX,pageY),鼠标在屏幕的坐标位置(screenX,screenY),其中鼠标在视口的坐标位置(clientX,clientY),以及鼠标在屏幕的坐标位置(screenX,screenY)在所有的浏览器中都支持,但是鼠标在页面的坐标位置(pageX,pageY)在IE8及更早版本不支持,但是没有关系,可以通过scrollLeft 和 scrollTop可以计算出pageX,pageY的值。
首先是跨浏览器的事件对象
var EventUtil = { addHandler:function(elem,type,handler){ if(elem.addEventListener) { elem.addEventListener(type,handler,false); }else if(elem.attachEvent) { elem.attachEvent("on"+type,handler); }else { elem["on"+type]=handler; } }, removeHandler:function(elem,type,handler){ if(elem.removeEventListener) { elem.removeEventListener(type,handler,false); }else if(elem.detachEvent) { elem.detachEvent("on"+type,handler); }else { elem["on"+type]=null; } }, getEvent:function(event){ return event?event:window.event; }, getTarget:function(event){ return event.target||event.srcElement; }, preventDefault:function(event){ if(event,preventDefault){ event.preventDefault(); }else{ event.returnValue = false; } }, stopPropagation:function(event){ if(event.stopPropagation){ event.stopPropagation(); }else{ event.cancelBubble=true; } } };
1.视口坐标位置
var div = document.getElementById("myDiv"); EventUtil.addHandler(div,"click",function(event){ event = EventUtil.getEvent(event); alert("Client coordinages: "+event.clientX+","+event.clientY); });
2.屏幕坐标位置
var div = document.getElementById("myDiv"); EventUtil.addHandler(div,"click",function(event){ event = EventUtil.getEvent(event); alert("Screen coordinates: "+event.screenX+","+event.screenY); });
3.页面坐标位置
var div = document.getElementById("myDiv"); EventUtil(div,"click",function(event){ event = EventUtil.getEvent(event); var pageX = event.pageX; var pageY = event.pageY; if(pageX==undefined) { pageX=event.clientX+document.body.scrollLeft||document.documentElement.scrollLeft; } if(pageY==undefined) { pageY = event.clientY+document.body.scrollTop||document.documentElement.scrollTop; } alert("Page coordinates: "+pageX+","+pageY); });