<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>下划线跟随导航条</title> <style type="text/css"> *{padding: 0;margin: 0} .cont{height: 600px;width: 40px; margin:0 auto;position: relative} ul { list-style: none; font-size: 20px; } li{cursor: pointer;width: 100px;height: 40px;text-align: center;line-height: 40px;background-color: skyblue;box-shadow: 0px 2px 20px skyblue} </style> </head> <body> <div class="cont"> <ul> <li name="0">html</li> <li name="1">css</li> <li name="2">javascript</li> <li name="3">php</li> <li name="4">mysql</li> </ul> <div class="xian" style="width:2px;height: 40px;background-color: orange;position: absolute;top:0px"></div> </div> </body> </html> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script> $(function () { $("li").hover(function () { $x = parseInt($(this).attr('name'))*40; $('.xian').stop().animate({'top':$x+'px'},300); },function () { $('.xian').stop().animate({'top':'0px'},300); }) }) </script>
效果图:
总结:为什么要先stop(); 因为hover离开的时候动画效果会回到最开始,不stop的话会出现来回滑动。