=100){//将顶部导航栏固定$(".n" />
页面滑动到一定的位置,让导航固定在顶部 |
您所在的位置:网站首页 › 导航栏固定在顶部 › 页面滑动到一定的位置,让导航固定在顶部 |
我使用了两种方法 先介绍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名 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |