【问题标题】:Change image using hover over link with setTimeout将鼠标悬停在带有 setTimeout 的链接上更改图像
【发布时间】:2013-07-25 08:19:11
【问题描述】:

我正在设计一个大型菜单,并希望根据悬停的链接更新 div 内的图像。我要做的是等待代码的 mouseleave 部分,这样如果用户立即移动到下一个 LI 标签,mouseleave 部分代码未执行。但是如果用户在 2 秒内没有 mouseenter 另一个 LI,那么这个 mouseleave 代码就会被执行。

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

// 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( ...

【问题讨论】:

    标签: javascript hover settimeout


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 2011-08-01
      • 2011-04-21
      • 1970-01-01
      • 2013-03-09
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      • 1970-01-01
      相关资源
      最近更新 更多