我使用下面的jQuery代码来找到我的顶部菜单导航的活动链接的位置:jQuery的范围混乱
$(document).ready(){
// Handles the triangle image sprite for the top navigation
$('#topnav a')
.on({
mouseenter: function() {
var pos = $("#topnav a.active-top").offset();
console.log("Top: " + pos.top + " Left: " + pos.left);
// Get the position of the current hovered "a" element
var upSprite = $("#upArrow").show(),
pos = $(this).offset(),
aWidth = $(this).width(),
offsetTop = 27, // Adjust this to raise or lower the sprite
offsetLeft = aWidth/2; // Centers the element under the link
upSprite
.css({
"top": pos.top + offsetTop,
"left": pos.left + offsetLeft
});
//console.log("Top: " + pos.top + " Left: " + pos.left);
},
mouseleave: function() {
// Hide the arrow once the mouse leaves
$('#upArrow').hide();
}
});
}
现在,当我复制粘贴此事件处理程序之外完全相同的代码
$(document).ready(function() {
var pos = $("#topnav a.active-top").offset();
console.log("Top: " + pos.top + " Left: " + pos.left);
}
我得到了一个完全不同的值pos.left。
据我所知,.offset()应该给我相对于文档的位置,而不像.position(),它给了我相对于父容器的位置。
当代码处于.on()事件处理程序的范围内时,代码是否处于不同类型的上下文中?我曾尝试使用$ .proxy()无济于事。任何提示都表示赞赏。谢谢。
啊,有没有办法确保offset()是在图像加载后拍摄的。我正在考虑设置超时时间,但这可能非常不可靠。 – ChrisC 2012-04-18 14:54:54
我能够使用$(window).load()等待图像来解决问题。谢谢! – ChrisC 2012-04-18 14:58:16