【问题标题】:Background color change on scroll滚动时背景颜色变化
【发布时间】:2020-11-22 07:25:32
【问题描述】:

我想更改滚动条的背景颜色,但我认为问题在于我使用的是 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>

【问题讨论】:

  • background-color后面加!important标签应该没有问题。
  • 是的,在 CSS 中。但是背景颜色是用 JavaScript 动态改变的。如果我在 CSS 中的 bg-color 后面添加 !important,它不会更改为下一个 bg-color。
  • 您的 sn-p 工作正常 (FF)
  • 哈哈哈哈我现在明白了,我在我的程序中输入了错误。谢谢你:)
  • 不要责怪 Bootstrap;问题总是在键盘和椅子之间。你的 sn-p 工作正常。到底是什么问题?

标签: javascript html css bootstrap-4


【解决方案1】:

放置 !important 来覆盖 css 规则不是 css 最佳实践,要覆盖引导 css 规则,最好在选择器中添加额外的标签: 例如:

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

或:

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

【讨论】:

  • 感谢您的帮助,我已经解决了这个问题。但无论如何,谢谢。
猜你喜欢
  • 2017-12-10
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 2013-09-07
  • 1970-01-01
  • 2013-10-23
  • 1970-01-01
相关资源
最近更新 更多