JS: mouse coordinates relative to an element

放肆的年华 提交于 2019-12-12 01:17:44

问题


Is it cross-browser to catch the mouse coordinates relative to a div box with this:

pos_x = event.offsetX?(event.offsetX):event.pageX-document.getElementById("thebox").offsetLeft;
pos_y = event.offsetY?(event.offsetY):event.pageY-document.getElementById("thebox").offsetTop;

回答1:


this works for me; change to your framework:

function assignPosition(element,event) {
cX=event.clientX; cY=event.clientY;
if ($$(element).pageYOffset)
   {
   rX=$$(element).pageXOffset;
   rY=$$(element).pageYOffset;
   }
if (document.body)
   {
   rX=document.body.scrollLeft;
   rY=document.body.scrollTop;
   }
if (document.documentElement && document.documentElement.scrollTop)
   {
   rX=document.documentElement.scrollLeft;
   rY=document.documentElement.scrollTop;
   }
cX+=rX;
cY+=rY;
$$(element).style.left=cX+"px";
$$(element).style.top=cY+"px";
}



回答2:


In case you do not have all/most of the browser types/versions to test on, you might take a look at this:
W3C DOM Compatibility - Events
Linked from above: W3C DOM Compatibility - CSS Object Model View

Gives you an idea of how compatible the codes are.




回答3:


function dodoubleclick(e){
             var mouseX, mouseY;

                if(e.offsetX) {
                    mouseX = e.offsetX;
                    mouseY = e.offsetY;
                }
                else if(e.layerX) {
                    mouseX = e.layerX;
                    mouseY = e.layerY;
                }
alert("mousex:"+mouseX+"and"+"mousey:"+mouseY);

}

this snippet will gives you mouse coordinates



来源:https://stackoverflow.com/questions/1815103/js-mouse-coordinates-relative-to-an-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!