<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>下划线跟随jQuery导航代码</title>
<link rel="stylesheet" href="css/test.css" type="text/css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script >
$(document).ready(function(){
var $liCur = $(".nav ul li.cur"),
curP = $liCur.position().left,
curW = $liCur.outerWidth(true),
$slider = $(".curBg"),
$navBox = $(".nav");
$targetEle = $(".nav ul li a"),
$slider.animate({
"left":curP,
"width":curW
});
$targetEle.mouseenter(function () {
var $_parent = $(this).parent(),
_width = $_parent.outerWidth(true),
posL = $_parent.position().left;
$slider.stop(true, true).animate({
"left":posL,
"width":_width
}, "fast");
});
$navBox.mouseleave(function (cur, wid) {
cur = curP;
wid = curW;
$slider.stop(true, true).animate({
"left":cur,
"width":wid
}, "fast");
});
})
</script>
</head>
<body>
<br><br><br><br>
<div align="center">
<div class="nav">
<ul>
<li class="cur"><a href="#">首页</a></li>
<li><a href="#">第二页</a></li>
<li><a href="#">第三页</a></li>
<li><a href="#">第四页</a></li>
</ul>
<div class="curBg"></div>
<div class="cls"></div>
</div>
</div>
</body>
</html>