我有这个html代码
<nav id="mainNav">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
它有这样的css样式
#mainNav { display:block; padding:5px; }
#mainNav ul { display:block; list-style-type:none; width:500px; border-collapse:collapse; }
#mainNav li { display:inline-block; width:100px; height:66px; text-align:center; padding-top:10px; float:left; background-color:gray; cursor:pointer; border-bottom:0px solid red; }
#mainNav a { color:white; text-decoration:none; text-transform:capitalize; }
#mainNav a.aHover { color:red; }
附加到此的是 JQuery 代码
$(document).ready(function() {
$('#mainNav li').mouseover(function() {
var el = $(this);
$(this).animate({
"border-bottom-width":"+=5px"
},{ queue: false, duration: 500 }, function() {
el.css('border-bottom-width', '5px');
});
$(this).children('a').addClass('aHover');
});
$('#mainNav li').mouseout(function() {
var el = $(this);
$(this).animate({
"border-bottom-width":"-=5px"
},{ queue: false, duration: 500 }, function() {
el.css('border-bottom-width', '0px');
});
$(this).children('a').removeClass('aHover');
});
});
现在我想让它做的是,将边框颜色淡入红色然后淡出,或者如代码中所写,在悬停时将边框扩展到最大 5 像素,然后将边框缩小回 0 像素。
问题是,如您所见,我尝试在动画结束时更改 LI 元素的类以确保边框达到其最大或最小宽度,但这不起作用,为什么?
您将如何淡入和淡出边框颜色?
最佳答案
试试下面,
$(document).ready(function() {
$('#mainNav li').hover(function() {
var el = $(this);
$(this).stop(true, true).animate({
"border-bottom-width": "5px"
}, {
queue: false,
duration: 500
});
$(this).children('a').addClass('aHover');
}, function() {
var el = $(this);
$(this).stop(true, true).animate({
"border-bottom-width": "0px"
}, {
queue: false,
duration: 500
});
$(this).children('a').removeClass('aHover');
});
});
改变了,
mouseover
事件到mouseenter
因为它更适合您的情况- 将
mouseenter/mouseleave
更改为hover
- 将
+=5px
、-=5px
更改为5px
和0px
。 - 添加了
.stop(true, true)
以确保动画完成并清除队列。
关于javascript - JQuery 动画边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10355516/