导航栏滚动

在项目,遇到导航栏滚动,滚到到窗口顶部悬停;滚动导航栏的产品,对应的导航栏选中。

html:

<div id="nav" >

        <a class="xyifu"   data-id="yifu" @click="goscrol">衣服</a>

        <a class="xxiezi"   data-id="xiezi" @click="goscrol">鞋子</a>

        <a  class="xmaozi" data-id="maozi" @click="goscrol">帽子</a>

</div>

<div id="yifu">衣服列表</div>

<div id="xiezi">鞋子列表</div>

<div id="maozi">帽子列表</div>

 

js:

//点击对应的导航栏,跳转到对应商品列表

goscrol($event) {

      var id = $event.target.dataset.id;

      var $scrollHeight = $("#" + id).offset().top;

      $("html, body").animate(

        {

          scrollTop: $scrollHeight

        },

        500

      );

},

 

window.onload = function() {

      var arr = [

        { id: "yifu", height: $("#yifu").height() },

        { id: "xiezi", height: $("#xiezi").height() },

        { id: "maozi", height: $("#maozi").height() }

      ];

 

      var box = document.getElementById("nav");

      var topmargin = box.offsetTop;

  

  //不同设备,安卓,iphone

      var userAgent = navigator.userAgent.toLowerCase();

      var isIphone = userAgent.match(/iphone os/i) == "iphone os";

      var isAndroid = userAgent.match(/android/i) == 'android';

 

      $(window).on("scroll", function() {

    //滚动页面,让导航栏悬浮在窗口顶部

        var scroll = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;

    if(isIphone){

      scroll >= topmargin - 50 ? $("#nav").addClass("postplayIOS") : $("#nav").removeClass("postplayIOS");

    }else{

      scroll >= topmargin - 50 ? $("#nav").addClass("postplayAndroid") : $("#nav").removeClass("postplayAndroid");

    }

     //当滚动时,导航栏没到窗口顶部,移除选中样式

      if (document.getElementById(arr[0].id).offsetTop - $(window).scrollTop() > 90 ) {

              $(".x" + arr[0].id).removeClass("redfont");

            }

    //当滚动到对应产品列表时,导航栏添加对应选中样式

         for (var i = 0; i < arr.length; i++) {

            var nowbox = document.getElementById(arr[i].id);

            if (nowbox.offsetTop - $(window).scrollTop() < 90) {

              $(".x" + arr[i].id).addClass("redfont").siblings().removeClass("redfont");

            }

         }

 

      });

 

};

 

CSS:

 

.postplayIOS {

  position: sticky;

  position: -webkit-sticky;

  left: 0;

  top: 0;

}

.postplayAndroid {

  position: fixed;

  left: 0;

  top: 0;

}

#nav .redfont {

  border-bottom: 2px solid #f9f100;

}

 

转载于:https://www.cnblogs.com/Super-scarlett/p/10000067.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值