导航栏的吸顶效果

导航栏的吸顶效果

当页面滑动到一定程度,让导航吸顶,上拉释放

1.首先,写一个吸顶的css样式


//吸顶
.fixed {
width: 1000px;
height: 70px;
position: fixed;
top: -1px;
left: 50%;
margin-left: -500px;
z-index: 1000;
}

2.而后,就是js的操作,

通过判断滑动的距离来判断是否实现吸顶

// 导航按钮

var menu= document.getElementById("nav");
// 获取距离页面顶端的距离
var titleTop = menu.offsetTop;
// 滚动事件
window.addEventListener("scroll", function() {
var btop = document.body.scrollTop || document.documentElement.scrollTop;
console.log(titleTop);
console.log(titleTop);
// 如果滚动距离大于导航条据顶部的距离
if(btop > titleTop) {
    // 为导航条设置fix
    $(".nav").addClass("fixed")
}  else {
    //移除fixed
    $(".nav").removeClass("fixed")
    }
})

猜你喜欢

转载自blog.csdn.net/WEIGUO19951107/article/details/78172433