我对jQuery offset()函数有疑问。我在我的网站上使用它,在点击电子邮件图标后显示“发送电子邮件给朋友”窗口。
但是,窗口显示在浏览器窗口的右侧,而不是图标的位置。您可以在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; });
有一张图片显示了意图与现实之间的区别。
答案 0 :(得分:15)
这是因为#container
有position: relative;
。因此,电子邮箱的绝对设置与#container相关。您必须删除该属性或使用以下内容计算left
的值:
$(this).offset().left - $('#container').offset().left
答案 1 :(得分:3)
只是使用位置istead。 .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;
});
添加了appendTo('。userTools')。显示在与另一个位置相同的位置的元素应该在同一元素内。然后位置工作,即使你改变布局也会工作。
如果您因任何原因不想更改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;
});