簡體   English   中英

滾動時的背景顏色更改

[英]Background color change on scroll

我想更改卷軸上的背景顏色,但我認為問題在於我正在使用 Bootstrap。 你能幫助我嗎? 任何解決方案? 我幾乎可以肯定它因為 Bootstrap 而不起作用。 我無法輸入 data-color !important 或 JavaScript。 我該怎么做才能覆蓋 Bootstrap 類?

 const sections = document.querySelectorAll('.bg'); function changeBackground(){ const bottom= window.scrollY + window.innerHeight; sections.forEach(section => { sectionMiddle= section.offsetTop + (section.offsetHeight / 2); if(bottom >sectionMiddle){ document.body.style.backgroundColor = section.dataset.color; } }); } window.addEventListener('scroll', changeBackground);
 *{ margin:0; padding:0; box-sizing: border-box; } body{ background-color: #9bc3f6; transition: background .8s; } .section1, .section2{ height:100vh; width:100%; }
 <!DOCTYPE html> <html> <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0- alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-CuOF+2SnTUfTwSZjCXf01h7uYhfOBuxIhGKPbfEJ3+FqH/s6cIFN9bGr1HmAg4fQ" crossorigin="anonymous"> </head> <body> <div class="container-fluid section1 bg" data-color="yellow"> <h1>Hello World</h1> </div> <div class="container-fluid text-center section2 bg" data-color="blue"> <h1>Hello World 2</h1> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-alpha3/dist/js/bootstrap.bundle.min.js" integrity="sha384-popRpmFF9JQgExhfw5tZT4I9/CI5e2QcuUZPOVXb1m7qUmeR2b50u+YFEYe1wgzy" crossorigin="anonymous"></script> </body> </html>

放置 !important 來覆蓋 css 規則並不是 css 最佳實踐,要覆蓋 bootstrap css 規則,最好在選擇器中添加額外的標簽:例如:

``const sections = document.querySelectorAll('body .bg');``

或者:

``const sections = document.querySelectorAll('html body .bg');``

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM