我正在尝试为我的侧边栏制作悬停效果。但出于某种原因,如果我在侧边栏上悬停太多,我在侧边栏中的元素不会淡入。 您可以在此处查看工作测试版:
$('#sidebar').stop().animate({ 'width': '40px'}, 500);
$('#sidebar .icon').stop().fadeIn(0);
$('#sidebar #logo').stop().fadeOut(0);
$('#sidebar #nav').stop().fadeOut(0);
$('#sidebar .quote').stop().fadeOut(0);
$('#sidebar .branding').stop().fadeOut(0);
// sidebar
$('#sidebar').hover(function(){
$('#sidebar').stop().animate({ 'width': '200px'}, 500);
$('#sidebar .icon').stop().fadeOut();
$('#sidebar #logo').stop().fadeIn();
$('#sidebar #nav').stop().fadeIn();
$('#sidebar .quote').stop().fadeIn();
$('#sidebar .branding').stop().fadeIn();
}, function(){
$('#sidebar').stop().animate({ 'width': '40px'}, 500);
$('#sidebar .icon').stop().fadeIn(function(){ $(this).removeClass('flipped');});
$('#sidebar #logo').stop().fadeOut();
$('#sidebar #nav').stop().fadeOut();
$('#sidebar .quote').stop().fadeOut();
$('#sidebar .branding').stop().fadeOut();
});
最佳答案
要淡入,元素必须被视为:hidden
。因此,如果您在它淡出时悬停,jQuery 将不会淡入,因为该元素是可见的。
有两种解决方案。第一个是使用 .stop(true, true)
。使用 true 作为参数意味着 “清空队列并跳转到末尾” 并且该元素将在 fadeIn()
之前隐藏。
但我最喜欢的解决方案是使用 fadeTo()
:
$(el).fadeTo('slow', 0); //Hide element
$(el).fadeTo('slow', 1); //Show element
奖金
这里有一个更易读的代码:
var $sidebar = $('#sidebar'),
$icons = $sidebar.find('.icon'),
$otherObj = $sidebar.find('#logo, #nav, .quote, .branding')
$('#sidebar').hover(function(){
$sidebar.stop().animate({ 'width': '200px'}, 500)
$icons.stop().fadeOut()
$otherObj.stop().fadeIn();
}, function(){
$sidebar.stop().animate({ 'width': '40px'}, 500)
$icons.stop().fadeIn().done(function(){ $(this).removeClass('flipped');})
$otherObj.stop().fadeOut();
});
关于javascript - 悬停时动画不会淡入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21991683/