如何在mouseenter上触发一次jQuery-UI效果?
$('#menu a').hover(
function() {
$(this).css({
'background-color': 'white',
'color': 'black',
}).effect('slide'); // EFFECT
}, function() {
$(this).css({
'background': 'none',
'color': 'white',
});
});
当鼠标结束时,它会一直运行。
答案 0 :(得分:2)
问题是正在使用幻灯片效果,因为<a>
从左侧滑入并获得第二个.hover()
事件。我使用jQueryUI中的元素获得position:relative
这一事实,以确定是否添加效果。
添加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
类留下。
的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',
});
});