如何在滾動時調整標題大小
學習如何使用 CSS 和 JavaScript 在滾動時縮小標題。
如何在滾動時縮小標題
第一步 - 添加 HTML:
創建頁眉:
<div id="header">Header</div>
第二步 - 添加 CSS:
設置頁眉的樣式:
#header { background-color: #f1f1f1; /* 灰色背景 */ padding: 50px 10px; /* 一些內邊距 */ color: black; text-align: center; /* 居中文本 */ font-size: 90px; /* 大字號 */ font-weight: bold; position: fixed; /* 固定位置 - 位于頁面頂部 */ top: 0; width: 100%; /* 全寬 */ transition: 0.2s; /* 添加過渡效果(滾動時減小字體大小) */ }
第三步 - 添加 JavaScript:
// 當用戶從文檔頂部向下滾動 50px 時,調整標題的字體大小 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"; } }