滚动标题

创建于 2024-12-03 / 19
字体: [默认] [大] [更大]

了解如何使用 CSS 和 JavaScript 在滚动时创建固定/粘性标题。


亲自试一试 »


如何在 Scroll 上创建固定页眉

步骤 1) 添加 HTML:

实例

<div class="header" id="myHeader">
  <h2>My Header</h2>
</div>
步骤 2) 添加 CSS:

实例

/* 设置标题样式 */
.header {
  padding: 10px 16px;
  background: #555;
  color: #f1f1f1;
}

/* 页面内容 */
.content {
  padding: 16px;
}

/* Sticky 类在到达滚动位置时用 JS 添加到 header */
.sticky {
  position: fixed;
  top: 0;
  width: 100%
}

/* 为页面内容添加一些顶部填充以防止突然快速移动(因为标题在页面顶部获得新位置(位置:固定和顶部:0)*/
.sticky + .content {
  padding-top: 102px;
}

步骤 3) 添加 JavaScript:

实例

// 当用户滚动页面时,执行 myFunction
window.onscroll = function() {myFunction()};

// 获取标题
var header = document.getElementById("myHeader");

// 获取导航栏的偏移位置
var sticky = header.offsetTop;

// 当到达滚动位置时,将粘性类添加到标题。 离开滚动位置时删除 "sticky"
function myFunction() {
  if (window.pageYOffset > sticky) {
    header.classList.add("sticky");
  } else {
    header.classList.remove("sticky");
  }
} 亲自试一试 »

0 人点赞过