window.pageYOffset案例:淘宝侧边栏滚动效果

<!DOCTYPE HTML>
<html>
 <head>
  <title>window.pageYOffset案例:淘宝侧边栏滚动效果</title>
  <meta charset="utf-8" />
  <style>
   * {
    margin: 0;
    padding: 0;
    }
   .typeArea {
     position: relative;
     width: 1200px;
     margin: 0 auto;
     font-size: 20px;
     text-align: center;
     font-weight: 700;
    }
   #hea {
    width: 100%;
    height: 200px;
    background-color: pink;
   }
   #banner {
    width: 100%;
    height: 500px;
    background-color: purple;
   }
   #main {
    width: 100%;
    height: 800px;
    background-color: blue;
   }
   #sidebar {
    position: absolute;
    right: 280px;
    top: 500px; 
    width: 70px;
    height: 400px;
    background-color: yellow;
   }
   #gohead {
     display: none;
    }
  </style>
 </head>
 <body>
  <div class="typeArea">
    <header id="hea">header200</header>
    <div id="banner">banner500</div>
    <div id="main">main800</div>
   </div>
   <div id="sidebar">
    <span id="gohead">回到顶部</span>
   </div>

  <script>
   var side = document.getElementById('sidebar');
   var gohead = document.getElementById('gohead');
   document.addEventListener('scroll', function() {
    if(window.pageYOffset >= 500) {
      side.style.position = 'fixed';
      side.style.top = '0';
      gohead.style.display = "block";
     }
      else {
        side.style.position = 'absolute';
        side.style.top = '500px';
        gohead.style.display = "none";
       }
    //console.log(window.pageYOffset);
   })
     
  </script>
 </body>
</html>
原创文章 22 获赞 4 访问量 2596

猜你喜欢

转载自blog.csdn.net/tuzi007a/article/details/105460232