jq 选择标题滚动到置顶页面-[源码]

 废话不多说直接给源码:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" type="text/css" href="css/index.css">
</head>
<style type="text/css">
  * {
    padding: 0;
    margin: 0;
  }

  .title_wrap {
    width: 500px;
    height: 50px;
    position: fixed;
    top: 0;
    left: 0;
    background: #FCCD09;
  }

  .title_wrap {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    transition: .2s;
    line-height: 50px;
  }

  .title_wrap a {
    margin: 0 30px;
  }

  .title_wrap .show {
    color: #ff0000
  }

  .item_ {
    width: 500px;
    height: 500px;
    color: #fff;
    text-align: center;
    font-size: 30px
  }
</style>

<body>

  <div class="title_wrap">
    <a href="#a" class="show">A</a>
    <a href="#b">B</a>
    <a href="#c">C</a>
    <a href="#d">D</a>
  </div>

  <div class="item_" id="a" style="background: #000;margin-top: 51px;">#A</div>
  <div class="item_" id="b" style="background: #ffc99f">#B</div>
  <div class="item_" id="c" style="background: #ff0000">#C</div>
  <div class="item_" id="d" style="background: #ccb">#D</div>

  <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>

  <script type="text/javascript">
    var item_a = $("#a").offset().top;
    var item_b = $("#b").offset().top;
    var item_c = $("#c").offset().top;
    var item_d = $("#d").offset().top;
    var index;
    function scr(index) {
      $(".title_wrap a").removeClass("show").eq(index).addClass("show")
    }

    $(window).scroll(function () {
      var scrTop = $(window).scrollTop() + item_a + 1;
      scrTop > item_a && scrTop < item_b ? scr(0) : (scrTop > item_b && scrTop < item_c ? scr(1) : scrTop > item_c && scrTop < item_d ? scr(2) : scr(3));
    })

    $('a[href^="#"]').click(function (e) {
      e.preventDefault();
      $('html, body').animate({ scrollTop: $(this.hash).offset().top }, 300);
    });
  </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/m0_66675766/article/details/131107835
jq