Javascript jQuery Offset().left 无法正常工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13449182/
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
jQuery Offset().left doesn't work properly
提问by FilipBenes
I have a question about jQuery offset() function. I use it on my site to display "email a friend" window after clicking on email icon.
我有一个关于 jQuery offset() 函数的问题。单击电子邮件图标后,我在我的网站上使用它来显示“向朋友发送电子邮件”窗口。
However, the window appears sticked to the right side of browser's window, not on the position of the icon. You can see it in action on http://pec.solarismedia.net/calendarday.html
但是,该窗口似乎粘在浏览器窗口的右侧,而不是图标的位置。您可以在http://pec.solarismedia.net/calendarday.html上看到它的运行情况
$(".emailFriend").hide();
$(".emailIcon").on("click", function(e) {
$(".emailFriend").css({
"position": "absolute",
"left": $(this).offset().left,
"top": $(this).offset().top
}).fadeIn(500);
return false;
});
There is a picture showing the difference between intention and reality.

有一张图显示了意图和现实之间的差异。

回答by Micha? Miszczyszyn
It's because #containerhas position: relative;. Thus absolute settings of the email box are relative to the #container. You have to either remove the property or calculate the value of leftwith something like this:
这是因为#container有position: relative;. 因此邮箱的绝对设置是相对于#container 的。您必须删除该属性或使用以下内容计算 的值left:
$(this).offset().left - $('#container').offset().left
回答by iRaS
just use position istead. The .position() method allows us to retrieve the current position of an element relative to the offset parent. Contrast this with .offset(), which retrieves the current position relative to the document.
只需使用位置代替。.position() 方法允许我们检索元素相对于偏移父元素的当前位置。将此与 .offset() 进行对比,后者检索相对于文档的当前位置。
$(".emailFriend").insertBefore('.emailIcon').hide();
$(".emailIcon").on("click", function(e) {
$(".emailFriend").css({
"position": "absolute",
"left": $(this).position().left,
"top": $(this).position().top
}).fadeIn(500);
return false;
});
added appendTo('.userTools'). an element showing at the same position than another should be within the same element. Then position works and will work even if you change the layout.
添加了 appendTo('.userTools')。与另一个显示在相同位置的元素应该在同一元素内。然后位置工作并且即使您更改布局也将工作。
If you don't want to change the dom structure for any reason you should use something like this:
如果您出于任何原因不想更改 dom 结构,则应使用以下内容:
$(".emailFriend").hide();
$(".emailIcon").on("click", function(e) {
$(".emailFriend").css({
"position": "absolute",
"left": $(this).offset().left-$(".emailFriend").offsetParent().offset().left,
"top": $(this).offset().top-$(".emailFriend").offsetParent().offset().top
}).fadeIn(500);
return false;
});

