使用带有setTimeout的悬停链接更改图像

Change image using hover over link with setTimeout

本文关键字:链接 图像 悬停 setTimeout      更新时间:2023-09-26

我正在设计一个超级菜单,并希望根据悬停的链接更新div中的图像。我要做的是等待代码的mouseleave部分,这样,如果用户立即移动到下一个LI标记,代码的mouseleaveouseenter另一个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( ...

当调用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