全国统一服务热线:400-633-9193

js实现导航跟随效果

    网络     2018-12-14    2257

如何实现上面的效果,请看下面的步骤

第一步:用 css 调整样式 ,这里小编用的是弹性盒子实现导航的平均分配。(聪明的你可以尝试用其他的方式看看能不能实现)css代码如下:

1
2
3
4
5
6
7
8
9
<style type="text/css">
 *{padding:0;margin:0;}
 a{text-decoration:none;}
 html,body{height:100%;width:100%;background:black;}
 ul{position:relative;width:990px;list-style:none;background:white;display: flex;flex-direction:row;justify-content: space-around;margin:50px auto;border-radius:10px;}
 ul li{position: relative;flex:1;text-align:center;}
 ul li a{font-size:18px;color:#333;padding:10px 0;display: block;}
 .cloud{position:absolute;left:32px;top:0;bottom:0;margin:auto;width:83px;height:42px;background:url('images/cloud.gif');}
 </style>

html代码如下:这里 a 标签中的 href 属性后面加上那句代码是为了在实现点击事件时不让他有其他事件发生

1
2
3
4
5
6
7
8
9
<ul>
 <span class="cloud"></span>
 <li> <a href="javascript:viod(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首页 </a></li>
 <li><a href="javascript:viod(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >电视剧</a></li>
 <li><a href="javascript:viod(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >最新电影</a></li>
 <li><a href="javascript:viod(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >新闻头条</a></li>
 <li><a href="javascript:viod(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >八卦娱乐</a></li>
 <li><a href="javascript:viod(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >军事热点</a></li>
 </ul>

第二步:分析下如何获得   图片(cloud.gif)   距离最左边的  left  值

 第三步:实现鼠标移动,移除,和点击事件的效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<script type="text/javascript">
//获得类为cloud的标签,
var pic=document.getElementsByClassName('cloud')[0];
//获得所有的 li 标签
var liList=document.getElementsByTagName('li');
//定义向右的移动初始距离
var liLeft=32;
//定义缓慢动画的初始值
var header=32;
//用于定义当鼠标点击时的初始位置
var currentLeft=32;
for(var i=0;i<liList.length;i++){
 //鼠标放上事件
 liList[i].onmouseover=function(){
 //获取目标距离
 liLeft = this.offsetLeft+this.offsetWidth/2-pic.offsetWidth/2;
 }
 //鼠标移除事件
 liList[i].onmouseout=function(){
 //当鼠标移除某个li的时候把目标距离改为初始状态
 liLeft=currentLeft;
 }
 //鼠标点击事件
 liList[i].onclick=function(){
 currentLeft=this.offsetLeft+this.offsetWidth/2-pic.offsetWidth/2;
 }
 
}
//定义缓慢动画
setInterval(function(){
 header = header + (liLeft-header)/10;
 pic.style.left = header + 'px';
},20);
</script>

以上就是本文的全部内容,希望对大家的学习有所帮助


  分享到:  
0.2714s