看过很多人写的导航栏案例,感觉都十分好, 在此我就表达一下我自己在学习中的心得吧
- css部分
*{
margin: 0;
padding: 0;
}
body{
background-color: #000;
}
.nav{
width: 800px;
height: 50px;
padding: 0 50px;
margin: 100px auto;
border-radius: 10px;
background: #fff url(./images/rss.png) 850px center no-repeat;
position: relative;
}
.nav ul{
list-style: none;
}
.nav li{
float: left;
font-size: 18px;
line-height: 50px;
padding: 0 20px;
font-weight: bold;
position: relative;
z-index: 666;
}
.cloud{
/*display: block;*/
width: 83px;
height: 42px;
background: url(./images/cloud.gif) ;
position: absolute;
top:4px;
}
- html部分
<body>
<div class="nav">
<span class="cloud"></span>
<ul>
<li>iPhone</li>
<li>Samsung</li>
<li>XIAOMI</li>
<li>HUOWEI</li>
<li>vivo</li>
<li>oppo</li>
</ul>
</div>
</body>
- js部分
window.onload = function(){
//获取cloud
var cloud = document.getElementsByClassName('cloud')[0];
//设定cloud当前值
var current = cloud.offsetLeft;
//设定目标值
var target = current;
//设定上一个返回值
var select = target;
//设置一个定时器,展现动画效果
setInterval(function(){
current = current + (target - current)/10 ;
cloud.style.left = current + 'px';
},20)
var lis = document.getElementsByTagName('li');
for( var i = 0;i < lis.length ; i++){
var li =lis[i];
//HTML中动作
li.onclick = function(){
// console.log(this);
//使目标值得到鼠标动作时li的left位置
target = this.offsetLeft;
//让返回值一直等于目标值,鼠标点击之后放开使结果一直保持不变
select = target;
}
li.onmouseover = function(){
target = this.offsetLeft;
// console.log(this);
}
li.onmouseout = function(){
// console.log(this);
target = select;
}
}
}