day24—JavaScript實現導航欄底部引線跟隨移動

轉行學開發,代碼100天——2018-04-09javascript

前面的學習筆記中記錄過,利用:before和:after實現導航欄鼠標移動跟隨效果,今天經過JavaScript代碼實現一樣的效果,以做對比。css

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript實現導航欄底部引線跟隨移動</title>
<!--適應移動端-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--css樣式-->
<style> body{background-color: #EBEBEB} ul{ list-style:none; position:relative; overflow:hidden;
    } ul li{ float:left; padding:5px 10px; background:skyblue; color:#fff; line-height:45px; text-align:center; transition:all .2s linear; cursor:pointer;
    } ul span{ width:100%; height:2px; bottom:0; background:#f60; position:absolute; display:black;
    } li:hover{ color:#000;
    }
</style>
<!--引用jquery庫-->
<script src="https://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
</head>

<body>

<h3>這是一個導航欄下引線鼠標跟隨移動效果</h3>

<div id="aaa">
    <ul>
        <li>菜單1</li>
        <li>菜單2</li>
        <li>菜單3</li>
        <li>菜單4</li>
        <li>菜單5</li>
        <span class="line"></span>
        
    </ul>
</div>

<script type="text/javascript"> $(document).ready(function(){ $("ul span").css({ 'left':$("ul li").eq(0).position().left, 'wodth':$("ul li").eq(0).outerWidth() }); $("ul li").hover(function(){ $("ul span").stop().animate({ left:$(this).position().left, width:$(this).outerWidth() }); },function(){ $("ul span").stop().animate({ left:$("ul li").eq(0).position().left, width:$("ul li").eq(0).outerWidth() }) }); }); </script>

</body>
</html>

 

 注:在本例中利用了outerWidth()方法獲取元素的外部寬度。注意其與width,innerWidth()的區別。html

相關文章
相關標籤/搜索