每次鼠标悬停触发一次 jquery 效果

Fire jquery effect once for each mouseover

本文关键字:一次 效果 jquery 鼠标 悬停      更新时间:2023-09-26
如何在

鼠标悬停时首次执行jquery效果后停止它?我希望盒子反弹一次并停止,即使鼠标留在盒子内,每次鼠标回到盒子时重复此操作。目前,当鼠标在盒子内时,它会无限运行效果。提前谢谢。

我在jsfiddle上做了一个例子

我试过了: one("mouseover", function() { $( "#div1" ).effect("bounce", "slow"); });

但是,当您离开盒子并重新进入盒子时,这不会再次触发事件。

>.one()工作:

$( "#div1, #div2" ).one('mouseover', function() {
    $(this).effect("bounce", "slow");
});

演示:http://jsfiddle.net/Rxhzg/1/

更新

(基于更新的问题)

如果"鼠标悬停一次"是指"一次反弹" - 添加times参数:

$( "#div1, #div2" ).mouseenter(function() {
    $(this).effect("bounce", { times: 1 }, "slow");
});

演示 2 http://jsfiddle.net/Rxhzg/4/

$( "#div1, #div2" ).one('mouseover', function() {
    $(this).effect("bounce", { times: 1 }, "slow");
});
$( "#div1, #div2" ).mouseleave(function() {
    $(this).one('mouseover', function() {
    $(this).effect("bounce", { times: 1 }, "slow");
});
});

检查此 http://jsfiddle.net/Rxhzg/6/

或者 http://jsfiddle.net/Rxhzg/8/检查这个,因为如果鼠标在盒子底部,上面的鼠标将继续反弹。

$( ".parentDiv" ).one('mouseover', function() {
    $(this).find('.navBox').effect("bounce", { times: 1 }, "slow");
});
$( ".parentDiv" ).mouseleave(function() {
    $(this).one('mouseover', function() {
    $(this).find('.navBox').effect("bounce", { times: 1 }, "slow");
});
});
此示例与其他

答案类似,但它将原始绑定抽象为函数以实现可重用性。

var $target = $( "#div1, #div2" );
function bounce() {
  $target.one('mouseover', function () {
    $(this).effect("bounce", { times: 1 }, "slow");
  });
}
$target.on('mouseout', bounce);      
bounce();