如何将网站导航栏固定在顶部(jquery固定导航栏)
在我们实际自己做网站时,往往为了方便用户点击导航栏里的栏目,需要将自己网站的导航栏一直固定在顶部。即使用户将网页往下拉时,也一直在浏览器的顶部。
以下是网站未被下拉时的样式:
以下是网页被下拉后,导航栏一直处于网页顶部。
在自己建网站时,实现网站导航栏固定在顶部的效果,需要使用JS或者使用jQuery教程里的知识。
原理:
通过JQuery来判断网页导航的上面与浏览器顶部的距离,来分别适用position:relative和position:fixed属性。
JQuery代码:
<script>
$(function(){
var a = $('#nav'),
b =a.offset();
$(document).on('scroll',function(){
var c = $(document).scrollTop();
if(b.top<=c){
a.css({'position':'fixed','top':'0px'})
}else{
a.css({'position':'relative','top':'0px'})
}
})
})
</script>
$(function(){
var a = $('#nav'),
b =a.offset();
$(document).on('scroll',function(){
var c = $(document).scrollTop();
if(b.top<=c){
a.css({'position':'fixed','top':'0px'})
}else{
a.css({'position':'relative','top':'0px'})
}
})
})
</script>
网站导航栏固定在顶部全部代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> jquery固定导航栏</title>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script>
$(function(){
var a = $('#nav'),
b =a.offset();
$(document).on('scroll',function(){
var c = $(document).scrollTop();
if(b.top<=c){
a.css({'position':'fixed','top':'0px'})
}else{
a.css({'position':'relative','top':'0px'})
}
})
})
</script>
<style>
*{margin:0;padding:0;}
#nav{width:100%;border:1px solid red;background:#09C;color:#fff;}
#nav li{display:inline-block;padding:5px 10px;}
section {height:2000px;}
</style>
</head>
<body>
<header>
<div class="top"><img src="https://www.xuewangzhan.com/wp-content/themes/xwz/images/Course.jpg" alt="LOGO"/></div>
<nav id="nav">
<ul>
<li>首页</li>
<li>新闻中心</li>
<li>产品安全</li>
<li>联系我们</li>
</ul>
</nav>
</header>
<section>
<!--网页主体内容-->
</section>
</body>
</html>
<html>
<head>
<meta charset="utf-8">
<title> jquery固定导航栏</title>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script>
$(function(){
var a = $('#nav'),
b =a.offset();
$(document).on('scroll',function(){
var c = $(document).scrollTop();
if(b.top<=c){
a.css({'position':'fixed','top':'0px'})
}else{
a.css({'position':'relative','top':'0px'})
}
})
})
</script>
<style>
*{margin:0;padding:0;}
#nav{width:100%;border:1px solid red;background:#09C;color:#fff;}
#nav li{display:inline-block;padding:5px 10px;}
section {height:2000px;}
</style>
</head>
<body>
<header>
<div class="top"><img src="https://www.xuewangzhan.com/wp-content/themes/xwz/images/Course.jpg" alt="LOGO"/></div>
<nav id="nav">
<ul>
<li>首页</li>
<li>新闻中心</li>
<li>产品安全</li>
<li>联系我们</li>
</ul>
</nav>
</header>
<section>
<!--网页主体内容-->
</section>
</body>
</html>