小編給大家分享一下JS如何實現滾動到指定位置導航欄固定頂部,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>js滾動到指定位置導航欄固定頂部</title>
<style type="text/css">
body{height: 2500px; margin: 0; padding: 0;}
.banner{height: 250px; width: 100%; background: #e5e5e5;}
.bignav{width: 100%; background: #000;}
.nav{ background:#000; width: 1200px; margin: 0 auto; height: 45px;}
.nav a{display: block; width: 200px;float: left; color: #fff; text-decoration: none; text-align: center; line-height: 45px;}
</style>
</head>
<body>
<div class="banner">
</div>
<div class="bignav" id="bignav">
<div class="nav">
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首頁</a>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首頁</a>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首頁</a>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首頁</a>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首頁</a>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首頁</a>
</div>
</div>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<p>其他內容</p>
<script type="text/javascript">
window.onscroll=function(){
var topScroll =document.body.scrollTop;//滾動的距離,距離頂部的距離
var bignav = document.getElementById("bignav");//獲取到導航欄id
if(topScroll > 250){ //當滾動距離大于250px時執行下面的東西
bignav.style.position = 'fixed';
bignav.style.top = '0';
bignav.style.zIndex = '9999';
}else{//當滾動距離小于250的時候執行下面的內容,也就是讓導航欄恢復原狀
bignav.style.position = 'static';
}
}
</script>
</body>
</html>以上是“JS如何實現滾動到指定位置導航欄固定頂部”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。