我使用了两种方法 先介绍jQuery的 这个的代码少
监听滚动事件
$(window).on("scroll",function(){
//判断向下滑动的距离
if($(window).scrollTop()>=100){
//将顶部导航栏固定
$(".nav").addClass("fixed");
}else{
$(".nav").removeClass("fixed");
}
});
记得引入jQuery
里面的fixed是类名 给的css样式
.fixed {
position: fixed;
top: 0;
z-index: 99;
}
下面这个用的js写的
//监听滚动事件
window.onscroll = function () {
// 滚动时当前位置距顶部的距离
var topScroll = document.documentElement.scrollTop;
console.log(topScroll)
// 获取导航id
var nav = document.getElementById("nav");
// 滚动距离大于多少时执行下面事件
if (topScroll > 100) {
// console.log(ihkh)
// 到了那个距离相当于给了导航定位
nav.style.position = 'fixed';
nav.style.top = '0';
nav.style.zIndex = '99'
} else {
// 小于的时候让他恢复原状
nav.style = ''
}
}
注:jQuery的.nav用的是类名 JavaScript的nav用的id名