2012-04-18 76 views
0

我使用下面的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()無濟於事。任何提示都表示讚賞。謝謝。

回答

3

$(document).ready()一旦DOM加載就會觸發;但在所有圖像加載之前。在通過重新繪製由此導致的元素來檢索offset()之後,您會發現偏移量正在更改。

要解決此問題,您可以改爲處理$(window).load()事件,或者繼續檢索點擊處理程序內的位置(這是我推薦的)。

+0

啊,有沒有辦法確保offset()是在圖像加載後拍攝的。我正在考慮設置超時時間,但這可能非常不可靠。 – ChrisC 2012-04-18 14:54:54

+2

我能夠使用$(window).load()等待圖像來解決問題。謝謝! – ChrisC 2012-04-18 14:58:16

1

很難分析這一點,因爲我不清楚「#topnav a.active-top」和其他可能修改其位置的元素引用的元素。我想,在$(something).mouseenter()之前的$(document).ready()之後會有一些處理(圖像加載,改變某些元素的寬度/高度等)。