2012-04-18 74 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()之后会有一些处理(图像加载,改变某些元素的宽度/高度等)。