js实现导航栏随着页面向下滑动逐渐显示,向上滑动逐渐隐藏

6 篇文章 0 订阅

一、html代码

 <!-- 导航栏 -->

    <nav id="dao">

      <x-icon type="ios-arrow-back" size="30" class="cell-back" id="cell-back"></x-icon>

      <h4 id="navtext">{{Jingyuan}}</h4>

    </nav>

二、css代码

#dao {

  position: fixed;

  left: 0;

  top: 0;

  right: 0;

  width: 100%;

  height: 3rem;

  z-index: 999;

}

#navtext {

  position: absolute;

  left: 50%;

  top: 50%;

  text-align: center;

  transform: translate(-50%, -50%);

  color: #fff;

  /* background: rgb(66, 65, 66) */

}

#cell-back {

  position: absolute;

  left: 0;

  top: 50%;

  transform: translate(0, -50%);

  fill: #fff;

}

三、js代码:

 

<script>

    window.onscroll = function () {

      var h = document.documentElement.scrollTop || document.body.scrollTop;

      console.log(h * 2.5);      //控制台查看监听滚动  

      var headerTop = document.getElementById("dao");//获取导航栏id

      var navtext = document.getElementById("navtext");//获取导航栏中的文字id

      var back = document.getElementById("cell-back");//获取导航栏中的返回图标icon id

      if (h >= 42) {       //header的高度是40px;     

        headerTop.style.background = "#fff";

        headerTop.style.color = "rgba(66,65,66,1)";

        // 设置导航栏中的文字样式

        navtext.style.background = "#fff";

        navtext.style.color = "rgba(66,65,66,1)";

        // 设置导航栏中的返回图标icon样式

        back.style.background = "#fff";

        back.style.fill = "rgba(19,146,245,1)";

      } else {

        if (h < 10) {

          //40*2.5=100;这样透明度就可以由0渐变到100%;

          headerTop.style.background = "rgba(255,255,255,0.0" + h * 2.5 + ")";

          headerTop.style.color = "rgba(66,66,66,0.0" + h * 2.5 + ")";

          navtext.style.background = "rgba(255,255,255,0.0" + h * 2.5 + ")";

          navtext.style.color = "rgba(66,66,66,0.0" + h * 2.5 + ")";

          back.style.background = "rgba(255,255,255,0.0" + h * 2.5 + ")";

          back.style.fill = "rgba(19,146,246,0.0" + h * 2.5 + ")";

        } else if (h > 10 && h <= 42) {

          headerTop.style.background = "rgba(255,255,255,0." + h * 2.5 + ")";

          headerTop.style.color = "rgba(66,66,66,0." + h * 2.5 + ")";

          navtext.style.background = "rgba(255,255,255,0." + h * 2.5 + ")";

          navtext.style.color = "rgba(66,66,66,0." + h * 2.5 + ")";

          back.style.background = "rgba(255,255,255,0." + h * 2.5 + ")";

          back.style.fill = "rgba(19,146,245,0." + h * 2.5 + ")";

 

        }

 

      }

    };

  </script>

  • 13
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值