2013-07-08 36 views
0

如何給我的腳本添加一個定時器?我想讓「mouseenter」函數在啓動之前等待1秒鐘。帶定時器的Mouseenter功能

$(".products_grid li").mouseenter(function(){ 
var $activeImage = $(this).find("img").attr("src"); 
var $imgZoom = '<div class="imgzoom"><img src="'+$activeImage+'" width="" height=""></div>'; 
    $($imgZoom).hide().appendTo(this).fadeIn(); 
}).mouseleave(function(){ 
    $("div.imgzoom").fadeOut().remove(); 
}) 
+1

https://developer.mozilla.org/en-US/docs/Web/API/window.setTimeout – j08691

回答

2

使用的setTimeout方法

包住裏面的方法你的代碼,將其分配給一個變量。

然後清除鼠標離開的超時。

var timer; 

$(".products_grid li").mouseenter(function() { 
    var $activeImage = $(this).find("img").attr("src"), 
     $imgZoom = '<div class="imgzoom"><img src="' + $activeImage + '" width="" height=""></div>', 
    that = this; 

    timer = setTimeout(function() { 
     $($imgZoom).hide().appendTo(that).fadeIn(); 
    }, 1000); 

}).mouseleave(function() { 
    if (timer) { 
     clearTimeout(timer); 
    } 
    $("div.imgzoom").fadeOut().remove(); 
}) 
+0

@ amp511 ..不客氣:) –

2

使用JavaScript的setTimeout,包裝你的代碼在另一個匿名函數,代理通過當前this參考:

$(".products_grid li").mouseenter(function(){ 
    $.proxy(setTimeout, this, function(){ 
     var $activeImage = $(this).find("img").attr("src"); 
     var $imgZoom = '<div class="imgzoom"><img src="'+$activeImage+'" width="" height=""></div>'; 
     $($imgZoom).hide().appendTo(this).fadeIn(); 
    }, 1000); 
}).mouseleave(function(){ 
     $("div.imgzoom").fadeOut().remove(); 
}) 
+0

不會'this'是不正確的位置'變量$ activeImage = $(本).find(「img」)。attr(「src」);'? –

+0

ops,沒錯!給我一分鐘,我會解決這個問題。 – elias

1
$(".products_grid li").on({ 
    mouseenter: function() { 
     var self = this; 
     $(this).data('timer', 
      setTimeout(function() { 
       var activeImage = $(self).find("img").attr("src"), 
        imgZoom  = $('<div />', {'class':'imgzoom'}), 
        img   = $('<img />', {src:activeImage}); 

       imgZoom.hide().append(img).appendTo(self).fadeIn(); 
      }, 1000) 
     ); 
    }, 
    mouseleave: function() { 
     clearTimeout($(this).data('timer')); 
     $("div.imgzoom").fadeOut(function() { 
      $(this).remove(); 
     }); 
    } 
}); 
+0

謝謝,這個也有效! – amp511