<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>下划线跟随导航栏</title> <script type="text/javascript" src="jquery.js"></script> <style type="text/css"> /* *{margin:0;padding:0;} div{width: 100%;height: 50px;background-color: #ccc;} nav{width:500px;margin:0 auto;} ul{list-style: none;} li{float: left;line-height: 50px;width: 100px;font-size: 14px;color: #13D1BE;cursor:pointer;} ul div{width: 100px;height: 2px;border: 1px solid red;background:#fff;position:absolute;top:30px;z-index:10;}*/ *{padding:0;margin:0;} ul {list-style: none;z-index:20;position:relative;font-size: 15px;} li {float:left;cursor:pointer;width:100px;height: 30px;text-align:center;line-height:30px;color: #fff;font-weight: bold;} .one{width:500px;position:relative;margin:100px auto;height:32px;box-shadow: 0 2px 20px #000;background: #AF3434;border-radius:3px } .two{z-index:10;width:100px;height:2px;background:#fff;position:absolute;top:30px;} </style> <script type="text/javascript"> $(document).ready(function(){ $('li').hover(function(){ $i=parseInt($(this).attr('name'))*100 $('.two').stop().animate({left:$i+'px'},400) },function(){ $('.two').stop().animate({left:'0px'},300) }) }) </script> </head> <body> <div> <nav> <ul> <li name="0">我的QQ</li> <li name="1">我的微信</li> <li name="2">我的微博</li> <li name="3">我的新浪</li> <li name="4">我的陌陌</li> </ul> <div></div> </nav> </div> </body> </html>
笔记
parseInt() 函数可解析一个字符串,并返回一个整数
attr() 方法设置或返回被选元素的属性值
思路
通过获取到li标签的name值,然后通过paseInt()函数来设置想要下滑线移动的距离,接着通过hover()函数来
使鼠标移动到那个li标签上面,就使移动相对应的距离.