实现滚动到一定位置时,导航栏置顶的效果

20 篇文章 0 订阅

告别js用css实现滚动到一定位置时,导航栏置顶的效果。

<div class="nav">这里是导航栏所在的DIV容器。</div>

css代码:

.nav{
    position:fixed; /* 绝对定位,fixed是相对于浏览器窗口定位。 */
    top:0; /* 距离窗口顶部距离 */
    left:0; /* 距离窗口左边的距离 */
    width:100%; /* 宽度设置为100% */
    height:40px; /* 高度 */
    z-index:99; /* 层叠顺序,数值越大就越高。页面滚动的时候就不会被其他内容所遮挡。 */
 }

js版本置顶(19/07/29)

<style type="text/css">
    /*添加导航条的样式;
    */
     #native {
      background: blue;
      width: 100%;
      height: 20px;
      color: red;
      text-align: center;
    }

    .box {
      position: fixed;
      top: 0;
      left: 0;
      z-index: 99;
      width: 100%;
      background: #fff;
      border-bottom: 1px solid #ebebeb;
      box-shadow: 0 0 5px #888;
    }
</style>
<body>
  <div id="native">悬浮置顶</div>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
  <p>悬浮置顶</p>
</body>
<script>
    //引入id标签;
    var navtive = $("#native");
    //设置监听事件;
    $(window).scroll(function () {
      var scrollHeight = $(document).scrollTop();
      console.log(scrollHeight)
      if (scrollHeight > 100) {
//添加类名样式
        navtive.addClass("box");
      } else if (scrollHeight == 0) {
//删除类名样式
        navtive.removeClass("box");
      }
//scrollHeight > 100 ? navtive.addClass("box") : navtive.removeClass("box");
    }); 
</script>

 

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值