简体   繁体   中英

Background color change on scroll

I wanna change the background color on a scroll, but I think that problem is I'm using Bootstrap. Can you help me? Any solutions? I'm almost sure it doesn't work because of Bootstrap. I can't type in data-color !important or in JavaScript. What can I do to overwrite the Bootstrap class?

 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>

It's not a css best practice to put !important to override css rules, to override bootstrap css rules it's better to add extra tags in your selector : for example:

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

or:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM