2015-05-28 41 views
-1

实际上,在产品页面中,我们希望减少服务器的负担,以便在鼠标悬停后的2到3秒后才能显示图像。所以,如果用户悬停光标,我们应该在2秒钟后打开服务器,并带来新的图像。但下面的代码没有按照我们的预期工作。如何用延时翻转图像?

HTML标签:

<img class="rollover-images" data-rollover="{bringNewImage()}" src="{bringOldImage()}" /> 

的Javascript:

$('.rollover-images').each(function() { 

     var newSrc = $(this).data('rollover'); 
     if(newSrc == 0) return; 

     var timeout, oldSrc; 
     $(this).hover(function() { 

      timeout = setTimeout(function() { 

       oldSrc = $(this).attr('src'); 
       $(this).attr('src', newSrc).stop(true,true).hide().fadeIn(1); 

      }, 2000); 

     }, function() { 

      clearTimeout(timeout); 
      $(this).attr('src', oldSrc).stop(true,true).hide().fadeIn(1); 

     }); 

    }); 
+0

*发生了什么? – Alex

+0

问题有问题吗?为什么它是-1? –

回答

1

有几个问题与发布代码

你不能把一个JavaScript函数的HTML属性并期望它被函数返回值替换。所以你的HTML应该是

<img class="rollover-images" data-rollover="new.png" src="old.png" /> 

你有这个问题,在超时功能。既然你已经开始了一个新的功能范围,这个值不会是你的img节点。所以你的JS应该是

$(this).hover(function() { 
    var self = this 
    timeout = setTimeout(function() { 
     oldSrc = $(self).attr('src'); 
     $(self).attr('src', newSrc).stop(true, true).hide().fadeIn(1); 
    }, 2000); 
}, function() { 
    clearTimeout(timeout); 
    $(this).attr('src', oldSrc).stop(true, true).hide().fadeIn(1); 
}); 

请注意,我们定义了一个名为self的新变量,它在setTimeout调用中使用。

+0

非常感谢!它的工作。 HTML样本仅供参考。我们正在处理代码作为我们框架的一部分。 –