你好,
我正在尝试使用jQuery制作一个简单的淡入淡出DIV并为导航栏上的每个按钮添加文本,但遇到了一些问题。以下是我想要实现的截图:
基本上,当用户将鼠标悬停在导航栏上的项目上时,一个DIV将出现在导航栏下方,并显示与该按钮相关的文本。到目前为止,我想出来的标记非常糟糕,我知道这不是正确的做法,我还尝试使用数组并使用导航按钮的标题属性填充信息div中的文本,后者效果很好,但标题也会出现。
除了太复杂之外,它确实可以工作...到一定程度。如果用户快速地在导航栏上悬停和移开鼠标,则会导致整个内容闪烁(不使用:hidden和:visible),或者如果使用了:hidden和:visible则不会出现。
以下是当前的标记:
信息DIV的CSS
#header-info-text {
width: 480px;
text-align: right;
float: right;
margin-right: 20px;
padding-right: 25px;
background: url('/images/info-arrow.png') top right no-repeat transparent scroll;
color: #fff;
display: none;
}
导航栏的HTML代码
<div id="navBar">
<ul>
<li class="nav-first nav-active"><a href="#">Home</a></li>
<li id="navAbout"><a href="#">About</a></li>
<li id="navPort"><a href="#">Portfolio</a></li>
<li id="navServ"><a href="#">Services</a></li>
<li id="navBlog"><a href="#">Blog</a></li>
<li id="navContact" class="nav-last"><a href="#">Contact</a></li>
</ul>
</div>
<div id="header-infoDIV">
<span id="header-info-text"></span>
</div>
Javascript
$("#navBar ul li").hover(function() {
var text;
var id = $(this).attr('id');
if (id == 'navAbout') {
text = 'Learn more ..';
} else if (id == 'navPort') {
text = 'View our recent work and ongoing projects';
} else if (id == 'navServ') {
text = 'Learn about our services';
} else if (id == 'navBlog') {
text = 'View the our Blog';
} else if (id == 'navContact') {
text = 'We\'re looking forward to working with you!';
} else {
text = '';
}
$("#header-info-text").text(text);
$("#header-info-text:hidden").fadeIn('slow');
});
$("#navBar ul").hover(function() {
$("#header-info-text:hidden").fadeIn('slow');
}, function() {
$("#header-info-text:visible").delay(500).fadeOut('slow');
});
什么是最好的方法来解决这种问题?基本上,我想淡入信息文本的DIV,在用户移动到另一个按钮时更改其文本,并在他们移出导航栏时隐藏它。
谢谢!
解决方案(感谢jmans):
$("#navBar ul").hover(function() {
$("#header-info-text").stop(true,true).fadeIn('slow');
}, function() {
$("#header-info-text").stop(true,true).delay(500).fadeOut('slow');
});
更新 感谢mVChr的建议,代码已经简化为几行。结合jmans提供的建议,它正在做我想要的事情:
$("#navBar ul li a").hover(function() {
var text = $(this).attr('rel');
$("#header-info-text").text(text);
$("#header-info-text").stop(true,true).fadeIn('slow');
},
function() {
$("#header-info-text").stop(true,true).delay(500).fadeOut('slow');
});