如何用 CSS 和 JavaScript 创建一个滚动时固定的/不动的页眉?


要使用 CSS 和 JavaScript 创建滚动时固定的/不动的页眉,代码如下 −

示例

 动态演示

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      margin: 0px;
      padding: 0px;
      height: 150vh; /*To produce scroll bar*/
   }
   .header {
      width: 100%;
      background-color: rgb(52, 21, 110);
      color: white;
      padding: 50px;
      font-size: 20px;
   }
   div.sticky {
      position: fixed;
      top: 0;
   }
</style>
</head>
<body>
<h1>Fixed Sticky on scroll example</h1>
<h2>Random Header Text</h2>
<h2>Randorm Header Text</h2>
<div class="header">Header Text</div>
<p style="font-size: 35px;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit vel dolore delectus esse 
consequatur at nulla, consequuntur sint quas ea. Incidunt, ex. Consequatur ipsa earum 
veritatis fugiat iusto, doloremque sunt beatae quaerat laboriosam nemo soluta quidem porro 
quia. Dolore reprehenderit cum voluptatibus eius assumenda ipsam tenetur asperiores magni 
aliquid eligendi doloribus quidem ipsa et praesentium provident molestias quaerat laboriosam, 
veniam aspernatur repellendus. Debitis sapiente, odit iste voluptatibus nesciunt veritatis 
incidunt mollitia nostrum, vitae suscipit iusto molestias consequuntur rem facere perspiciatis 
ad! Ratione reiciendis asperiores aperiam vitae facilis accusantium non aliquid, facere 
cupiditate reprehenderit tempore veritatis eum accusamus omnis
tempora quos!
</p>
<script>
   window.onscroll = function() {
      setSticky();
   };
   var header = document.querySelector(".header");
   var sticky = header.offsetTop;
   function setSticky() {
      if (window.pageYOffset > sticky) {
         header.classList.add("sticky");
      }
      else {
         header.classList.remove("sticky");
      }
   }
</script>
</body>
</html>

输出

上面的代码将输出以下内容 −

向下滚动一点后,页眉将成为固定的页眉 −

更新于: 2020 年 5 月 8 日

946 次浏览

开启您的 职业生涯

完成课程并获得认证

开始
广告