Javascript offsetX,offsetY 和 pageX,pageY 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6645951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between offsetX,offsetY and pageX,pageY?
提问by kaz
I need a popup div that will appear right below the anchor that i clicked. Now, I want to determine the x and y coordinates onClick event of an anchor. What's the best practice of doing it? What are the advisable event properties to use?
我需要一个弹出 div,它会出现在我单击的锚点正下方。现在,我想确定锚点的 x 和 y 坐标 onClick 事件。这样做的最佳做法是什么?建议使用哪些事件属性?
回答by AlienWebguy
offsetXand offsetYare relative to the parent container, whereas pageXand pageYare relative to the document. Don't confuse this with .offset()
and .position()
, in which .offset()
is relative to the document and .position()
is relative to the parent container's .offset()
.
offsetX和offsetY相对于父容器,而pageX和pageY相对于文档。不要将它与.offset()
and混淆.position()
,其中.offset()
和.position()
是相对于文档的,并且是相对于父容器的.offset()
。
Something like this example should work (JQuery):
像这个例子应该工作(JQuery):
$('a').click(function(){
var offset = $(this).offset();
$('#popup_div').css('top',offset.top + 'px').css('left',offset.left + 'px').show();
});
回答by Praveen Prasad
2 extracts from Jquery Documentation website
2 从 Jquery 文档网站摘录
The .position() method allows us to retrieve the current position of an element relative to the offset parent
.position() 方法允许我们检索元素相对于偏移父元素的当前位置
http://api.jquery.com/position/
http://api.jquery.com/position/
The .offset() method allows us to retrieve the current position of an element relative to the document.
.offset() 方法允许我们检索元素相对于文档的当前位置。