jQuery实现导航栏头滚动条卷动导航栏固定

<!DOCTYPE html>
<html lang =“en”>
<head>
<meta charset =“UTF-8”>
<title>头部导航栏部分固定</ title>
<link rel =“stylesheet”href =“css /base.css“type =”text / css“>
<style type =”text / css“>
.top {width:100%; background:#ccc;}
.nav {width:900px; margin:0 auto; background :url('img / logo_03.png')no-repeat 0 0; border:solid 1px pink;}
.nav ul {width:900px; padding-top:100px;}
.nav ul li {padding:10px 90px; float :left; border:solid 1px blue; text-align:center;}
.content {height:8888px; width:900px; border:solid 1px red; margin:20px auto;}
/ *导航栏位置固定的时候添加的样式* /
.navFix {position:fixed; top:0; z-index:999;}
/ *导航栏位置还原的时候添加的样式* /
.navStatic {position:static; z-index:999;}




</ style>


<script type =“text / javascript”src =“js / jquery-3.3.1.min.js”> </ script>
<script type =“text / javascript”>
$(document).ready(function(){
console.log(“hello,world”)
// 1:首先获取导航栏部分的高度,当页面文档滚动的时候,向上卷的高度大于导航栏的高度的时候,给导航栏部分的样式设置固定位
var navHeight = $(“。top”)。height(); //获取当前元素的高度
var navWidth = $(“。nav”).width();
console.log(navHeight); //获取的是number类型的值
// 2:当页面滚动的时候,文档向上滚动的距离大于导航栏元素的距离的时候,这个导航栏部分固定样式
$(window).scroll(function(){
   var doc = $(文档).scrollTop(); // 3:获取文档向上卷动的高度
   console.log(doc);    if(doc> = navHeight){ //第一种方法,使用css方法给顶部元素添加样式/ / $(“。top”)。css({ // “位置“:”fixed“, // ”top“:”0“ //})
  

   
   
   
   
       
   
    //第二种方法,在css样式表文件中添加一个样式,在给这个元素添加样式属性$(“。top”)。addClass(“navFix”)   }    else { //第一种方法是给元素样式添加属性// $(“top”)。addClass('navStatic')这种方法不执行不知道是为什么//原因是因为我没有定位到元素$(“top”)没有定位到  $(“。 ()“)。removeClass(”navFix“)//第二种方法使用css方法设置样式// $(”。top“)。css({ //”position“:”static“      //  })   } })} </ script> </ head> <body> <div class =“top”> <div class =“nav”> <ul> <li>首页</ li> <li>栏目a </ li> < LI>栏目一个</ LI><li>栏目a </ li> <div class =“clear”> </ div> </ ul> </ div> </ div>
   




   
   
   
   
     


   
   
   
   
       








































<div class =“content”> </ div> </ body> </ html>


猜你喜欢

转载自blog.csdn.net/transfer_jane/article/details/80621639