2013-07-25 124 views
0

我正在设计一个超级菜单,并希望根据链接被徘徊在一个div内更新图像。我试图做的是等待mouseleave部分代码,以便如果用户立即移动到下一个LI标记,则代码的部分代码不会执行。但是如果用户不在mouseenter另一个LI 2秒,那么这个mouseleave代码被执行。使用鼠标悬停在setTimeout上的链接更改图像

问题是#1返回值正常,但#2给出'未定义'的值。为什么是这样,我该如何解决这个问题?我该如何获取当前正在LI中徘徊在setTimeout函数内部的属性?因为一旦我有了价值,我就可以做一个比较来控制流量。非常感谢。

// FADE IN THE IMAGE ACCORDING TO THE MENU ITEM 
// HTML=<li><a data-pos="left -256px" href="somelink">Link A</a></li> 
var $sprite = $('#photo'); 

    $('li>a').hover(
     function() { 
      sprite_pos=$(this).attr('data-pos');  // fetch value for the tag 
      // Put an if otherwise this code gets executes for all li>a creating an unnecessary fade-in out effect 
      if(typeof(sprite_pos) != "undefined") { 
       $sprite.fadeTo(200, 0, function() { 
       $sprite.css("background-position",sprite_pos); }); 
       $sprite.fadeTo(200, 1); 
      } 
     }, 
     function() { 

      //sprite_pos=$(this).attr('data-pos');   // #1 

      setTimeout(function() { 
       sprite_pos=$(this).attr('data-pos');  // #2 fetch value for the tag 

      if(typeof(sprite_pos) != "undefined") { 
       $sprite.fadeTo(200, 0, function() { 
       $sprite.css("background-position",default_pos); }); 
       $sprite.fadeTo(200, 1); 
      } // if(typeof(sprite_pos) != "und ... 
      }, 2000); 
     } 

    ); // $('li>a').hover(... 

回答

0

setTimeout称为this成为window对象。要修复只需创建一个参考原始this上下文:

function() { 

    var me = this; 

    setTimeout(function() { 

     sprite_pos=$(me).attr('data-pos');  // #2 fetch value for the tag 
     ///   ^^ 

     /// ... rest of code 
+0

这样做的伎俩。非常感谢!!! – user1771959

相关问题