2013-04-28 76 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'); 
    }); 

第一个会比较有用。