我使用下面的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