目录

如何 - 在滚动时调整标题大小


了解如何使用 CSS 和 JavaScript 缩小滚动时的标题。


亲自试一试 »


如何缩小滚动标题

步骤1)添加HTML:

创建一个标题:

示例

<div id="header">Header</div>

步骤2)添加CSS:

设置标题样式:

示例

#header {
  background-color: #f1f1f1; /* Grey background */
  padding: 50px 10px; /* Some padding */
  color: black;
  text-align: center; /* Centered text */
  font-size: 90px; /* Big font size */
  font-weight: bold;
  position: fixed; /* Fixed position - sit on top of the page */
  top: 0;
  width: 100%; /* Full width */
  transition: 0.2s; /* Add a transition effect (when scrolling - and font size is decreased) */
}


步骤 3) 添加 JavaScript:

示例

// When the user scrolls down 50px from the top of the document, resize the header's font size
window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
    document.getElementById("header").style.fontSize = "30px";
  } else {
    document.getElementById("header").style.fontSize = "90px";
  }
}
亲自试一试 »