木子婷
2018-10-25 16:02
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
ul {
list-style: none;
margin: 0;
padding: 0;
overflow: auto;
background-color: antiquewhite;
position: fixed;
top: 0;
/*改为bottom:0;就是固定在底部*/
width: 100%;
}
li {
float: left;
border-right: 1px solid black;
/*在右边添加分割线*/
}
li:last-child {
border-right: none;
}
li a {
display: block;
width: 60px;
text-decoration: none;
color: black;
padding: 8px 20px;
}
li a:hover:not(.active) {
background-color: deepskyblue;
color: greenyellow;
}
li a.active {
background-color: greenyellow;
color: red;
}
</style>
<script>
window.onload = function() {
var aA = document.getElementsByTagName("a");
for(var i = 0; i < aA.length; i++) {
aA[i].onmouseover = function() {
clearInterval(this.time)
var This = this;
This.time = setInterval(function() {
This.style.width = This.offsetWidth + 8 + "px";
if(This.offsetWidth >= 100) {
clearInterval(This.time)
}
}, 30)
}
aA[i].onmouseout = function() {
clearInterval(this.time)
var This = this;
This.time = setInterval(function() {
This.style.width = This.offsetWidth - 8 + "px";
if(This.offsetWidth <= 60) {
This.style.width = "60px"
setInterval(This.time)
}
}, 30)
}
}
}
</script>
</head>
<body>
<ul>
<li>
<a href="#">主页</a>
</li>
<li>
<a href="#">新闻</a>
</li>
<li>
<a href="#">联系</a>
</li>
<li>
<a href="#">B站</a>
</li>
<li style="float: right;">
<a class="active" href="#">关于</a>
</li>
</ul>
</body>
</html>
原因有两个:
(1)onmouseout里面应该是clearInterval,而不是setInterval;
(2)主要原因
a标签设置了左右padding是20px,而width是60px,所以a标签初始的offsetWidth是100;
当onmouseover时,a标签+8px,然后再设置a标签的width,此时a标签的width=108px,而a标签的offsetWidth=148px,满足条件,此时清除了定时器。
当onmouserout时,启动定时器,a标签的offsetWidth - 8 = 140px,再把140设置为a标签的width,此时a标签的width=140px;而a标签左右padding是20px,所以此时a标签的offsetWidth=180px,不满足条件,所以不会清除定时器。过了30毫秒之后,重复上面的步骤,导致width越来越大。
解决方法:
onmouseout改成clearInterval;
把a标签的左右padding去掉
导航条菜单的制作
123836 学习 · 838 问题