jQuery實現吸頂動畫導航欄

淺段蔡姬發表於2020-12-21
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>固定導航欄</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }



    /*1--給middle盒子設定這一個屬性就行--1*/
    .middle{
      /*position: sticky;*/
      /*top:0;*/
    }
		
		/*設定層級  遮住middle1*/
		.middle{
			z-index: 999;
		}

    .middle1{

      position: absolute;
      top: 129px;
      left: 0;
      display: none;
    }


    .fixed{
      position: fixed;
      top: 0;
      display: none;
    }

  </style>
</head>
<body>
<div class="container">
  <div class="top">
    <img src="./imgs/14_固定導航欄/1.png" alt="">
  </div>
  <div class="middle">
    <img src="./imgs/14_固定導航欄/2.png" alt="">
  </div>
  <div class="middle1">
    <img src="./imgs/14_固定導航欄/2.png" alt="">
  </div>
  <div class="bottom">
    <img src="./imgs/14_固定導航欄/3.png" alt="">
  </div>
</div>

<script src="../jquery-3.4.1.min.js"></script>
<script>
//利用js實現導航欄固定功能
  $(function () {
    $(window).scroll(function () {

      // console.log($(window).scrollTop())


      if ( $(window).scrollTop() >= 198 ){


        $('.middle').slideDown(200)
        $('.middle').addClass('fixed')



        //當給.middle新增fixed,.middle就脫離了文件流,下面的內容就一下頂上去了
        $('.bottom').css('margin-top','69px')

				//當滾動值大於198px,讓middle1隱藏
        $('.middle1').css('display','none')

      }
      else{//滾動值小於198px
        if ( $(window).scrollTop() < 129 ){
			$('.middle1').css('display','block')
			$('.middle').css('display','none')
			$('.bottom').css('margin-top','69px')
		}
      }
    })
  })
</script>

</body>
</html>

相關文章