2013-04-28 77 views
1

我創建了一個鏈接時,將用戶懸停,有些圖像會蹦出來,當他們走出徘徊,圖像將消失。一切工作都很完美,但是,當他們將鼠標懸停在鏈接上多次時,圖像會一直彈出,直到完成爲止,具體取決於鏈接懸停的次數。有什麼辦法可以延遲執行懸停事件來防止這種情況發生?我的代碼如下防止鼠標懸停在重複多次徘徊

$('.my_link a').bind('mouseover', function() { 
    var my_title = $(this).html(); 
    var title_width = parseInt($(this).width()); 
    var next = $(this).next(); 

    $.ajax({ 
     type: "POST", 
     url: 'ajax/my_info_hover.php', 
     data: { 
      my_title: my_title 
     } 
    }).success(function (data) { 
     //Disable mouseover from this class? 
     $('.my_info_wrap').remove(); 
     $(next).html(data).css('left', title_width + 10 + 'px'); 
    }); 

}).mouseout(function() { 
    //Enable mouseover again? 
    $('.my_info_wrap').remove(); 
}); 
+0

你在AJAX功能得到什麼exaclty? – adeneo 2013-04-28 19:18:53

回答

0
$(document).ready(function() { 
    var timer, $this; 
    $('.my_link a').bind('mouseover', function() { 
     clearTimeout(timer); 
     $this = $(this); 
     timer = setTimeout(function() { 
      var anime_title = $this.html(); 
      var title_width = parseInt($this.width(), 10); 
      var next = $this.next(); 

      $.ajax({ 
       type: "POST", 
       url: 'ajax/my_info_hover.php', 
       data: { 
        my_title: my_title 
       } 
      }).success(function (data) { 
       //Disable mouseover from this class? 
       $('.my_info_wrap').remove(); 
       $(next).html(data).css('left', title_width + 10 + 'px'); 
      }); 
      console.log("This works!"); 
     }, 1000); //function fires after 1000ms = 1s 
    }).mouseout(function() { 
     //Enable mouseover again? 
     clearTimeout(timer); 
     $('.my_info_wrap').remove(); 
    }); 
}); 

SetTimeout Function等待一個特定的時間,然後在它執行的功能。 clearTimeout清除計時器。 因此,每當用戶將鼠標懸停在鏈接上時,計時器開始,如果他再次執行該操作,計時器將被清除並立即開始新的操作。 當用戶離開鏈接時,定時器必須被清除。 在上面的例子中,該函數在1秒後觸發。

但我寧願.on(),而不是綁定。因此,您只需要使用。對

$('.my_link a').on('mouseover', function() { 
    ... 
}).mouseout(function() { 
    ... 
}); 

編輯

工作jsfiddle這裏 更換綁定...和another version用。對(),而不是.bind()

+0

不工作,我認爲你的語法錯誤 – user2310422 2013-04-28 19:43:23

+0

現在應該可以工作。我添加了一個jsfiddle來顯示它。 – SirDerpington 2013-04-28 19:46:37

+0

我的錯,我試過你的代碼,但它給了我相同的結果。圖像將繼續彈出,直到完成爲止,具體取決於它們懸停鏈接的次數。和你的小提琴不工作,我正在使用鉻 – user2310422 2013-04-28 19:49:05

0

我d做這樣的事情:

var element = '#elementId'; 

var enter = function() { 
console.log('entered'); 
$(element).stop().fadeIn('fast'); 
} 

var leave = function() { 
console.log('left'); 
$(element).stop().fadeOut('slow'); 
} 

$('.toHoverOn').hover(function(){leave()}, function(){enter()}); 

請注意,您可以替換個人leaveenter功能,只是剛剛immedietely寫你的邏輯在回調,那就是:如果有很多你「的mouseenter /懸停」和「鼠標離開」事件發生

var element = '#elementId'; 

    $('.toHoverOn').hover(function(){ 
     console.log('entered'); 
     $(element).stop().fadeOut('slow'); 
    }, function(){ 
     console.log('left'); 
     $(element).stop().fadeIn('fast'); 
    }); 

第一個會比較有用。