如何使用 CSS 和 JavaScript 创建滚动指示器?
cssweb developmentfront end technologyjavascript
要使用 CSS 和 JavaScript 创建滚动指示器,代码如下 −
示例
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { font-size: 28px; margin:0px; padding:0px; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } .header { position: fixed; top: 0; margin-bottom: 100px; z-index: 1; width: 100%; background-color: #ebfffd; } .progressContainer { width: 100%; height: 20px; background: #ccc; } .progressBar { height: 20px; background: #724caf; width: 0%; } .content { padding: 100px 0; margin: 50px auto 0 auto; width: 80%; } </style> </head> <body> <div class="header"> <h1>Scroll indicator example</h1> <div class="progressContainer"> <div class="progressBar"></div> </div> </div> <div class="content"> <h1>Some headers</h1> <h1>Some headers</h1> <h1>Some headers</h1> <h1>Some headers</h1> <h1>Some headers</h1> </div> <script> window.onscroll = function() {showProgress()}; function showProgress() { var scrollCalculate = document.body.scrollTop || document.documentElement.scrollTop; var height = document.documentElement.scrollHeight - document.documentElement.clientHeight; var scrolled = (scrollCalculate / height) * 100; document.querySelector(".progressBar").style.width = scrolled + "%"; } </script> </body> </html>
输出
上述代码将产生以下输出 −
向下滚动页面时,进度条将增加,如下所示 −