悬停:如何触发UI效果一次?

时间:2012-10-27 07:00:28

标签: jquery jquery-ui jquery-hover

如何在mouseenter上触发一次jQuery-UI效果?

http://jsfiddle.net/MG4JZ/

$('#menu a').hover(
  function() {
    $(this).css({
        'background-color': 'white',
        'color': 'black',
    }).effect('slide'); // EFFECT
  }, function() {
    $(this).css({
        'background': 'none',
        'color': 'white',
    });
});

当鼠标结束时,它会一直运行。

2 个答案:

答案 0 :(得分:2)

问题是正在使用幻灯片效果,因为<a>从左侧滑入并获得第二个.hover()事件。我使用jQueryUI中的元素获得position:relative这一事实,以确定是否添加效果。

Demo

添加CSS

#menu a:hover {
    background-color:white;
    color:black;
}​

并简单地使用.mouseenter()

$('#menu a').mouseenter(function() {
    var $this = $(this);
    if ($this.css('position') === 'relative') return;
    $(this).effect('slide'); // EFFECT
});​

似乎为我解决了。

编辑:所以感谢Matthew在评论中指出,当徘徊在最右边时,事件仍会多次发生。所以这是一个更新的答案。它使用较新的jQuery .on()语法,但您仍然可以使用旧方法来实现相同的结果。它现在使用两个事件,一个在锚点上添加悬停样式和效果但如果在进入锚点时,该元素还没有该类。在悬停锚点时,我还会从所有其他锚点中删除悬停类。第二个事件包括退出整个菜单时删除悬停类。如果没有第二个事件,当离开菜单时,最后一个锚点会被.hover类留下。

Updated demo

的JavaScript

var $anchors = $('#menu a');

$('#menu').on('mouseenter', 'a', function() {
    $anchors.not(this).removeClass('hover');

    var $this = $(this);
    if ($this.hasClass('hover')) return;
    $this.addClass('hover').effect('slide'); // EFFECT
});

$('#menu').on('mouseleave', function() {
    $anchors.removeClass('hover');
});​

CSS

#menu {
    background-color: black;
}

#menu a {
    display: block;
    color: white;
}

#menu a.hover {
    background-color:white;
    color:black;
}​

HTML

<div id="menu">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
</div>

希望这有帮助。

答案 1 :(得分:0)

请尝试http://jsfiddle.net/MG4JZ/6/

$("#menu a").mouseenter(function(){
   $(this).css({
      'background-color': 'white',
      'color': 'black',
    }).stop(true,true).effect('slide');
}).mouseleave(function(){
   $(this).css({
    'background': 'none',
    'color': 'white',
   });
});

$("#menu a").hover(function(){
   $(this).css({
      'background-color': 'white',
      'color': 'black',
    }).stop(true,true).effect('slide');
},function(){
   $(this).css({
    'background': 'none',
    'color': 'white',
   });
});