javascript - 对具有相同类的多个元素使用 getBoundingClientRect()?

标签 javascript html css

我正在尝试向我的网站添加粘性导航,当它滚动到不同的部分时会发生变化。当滚动到带有 .dark 类的部分时,它应该将 Logo 和文本颜色更改为白色……否则为黑色。

下面是我一直在使用的 javascript,但这似乎只适用于 .dark 类的第一个元素,我如何调整它以针对具有相同类的所有元素?

window.addEventListener('scroll', function () {

        var section = document.querySelector('.dark').getBoundingClientRect(),
            logo = document.querySelector('#logo-container').getBoundingClientRect();

          if (section.top <= logo.top + logo.height && section.top + section.height > logo.top) {
            document.getElementById('logo-container').classList.add('white-logo');
            document.getElementById('navholder').style.color = "#fff";

          } else {
            document.getElementById('logo-container').classList.remove('white-logo');
            document.getElementById('navholder').style.color = "#111";
          }

     });

如果这是一个显而易见的问题,我深表歉意,我对 javascript 不是很了解!我试图寻找解决方案,但没有取得太大成功。任何帮助将不胜感激。

最佳答案

如果将它分解成几个函数,它会让生活变得更轻松。您可以检查 Logo 是否属于任何部分,然后相应地设置其类:

const setLogoBlackStatus = status => {
  if (status) {
    document.getElementById('logo-container').classList.add('black-logo');
    document.getElementById('logo-container').classList.remove('white-logo');
  } else {
    document.getElementById('logo-container').classList.add('white-logo');
    document.getElementById('logo-container').classList.remove('black-logo');
  }
}

const logoIsInSection = logo => sectionRect => sectionRect.top <= logo.top + logo.height &&
  sectionRect.top + sectionRect.height > logo.top

window.addEventListener('scroll', function() {

  var sectionRects = [...document.querySelectorAll('.dark')]
    .map(el => el.getBoundingClientRect());

  var logo = document.querySelector('#logo-container').getBoundingClientRect();

  var logoInAnySections = sectionRects
    .some(logoIsInSection(logo))

  setLogoBlackStatus(!logoInAnySections);
});
img {
  width: 50px;
  position: fixed;
  top: 20vw;
  left: 20vw;
  z-index: 1;
}

.white-logo {
  filter: invert(90%);
}

.section {
  width: 100%;
  height: 300px;
}

.dark {
  background-color: rgba(20, 20, 30);
}

.white {
  background-color: white;
}
<img src="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/cc.svg" id="logo-container"/>
<div class="section white"></div>
<div class="section dark"></div>
<div class="section white"></div>
<div class="section dark"></div>

关于javascript - 对具有相同类的多个元素使用 getBoundingClientRect()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57324459/

相关文章:

html - 100% 高度和奇怪的问题

html - 如何避免 Firefox 从表中复制时出现额外的换行符?

javascript - 检查滚动当前是否位于底部 - 没有 jQuery

javascript - 客户指令 ng-repeat 作用域未进入 Angular JS 函数内部?

javascript - 在 Firefox 的 Canvas 上下文对象上使用 svg 调用 drawImage() 时出现问题

html - 我的 CSS 没有链接到我的 HTML

php - 如何将多个文件附加到电子邮件并将其动态发送到多个emailid php

javascript - 如何去除导航栏中的蓝色轮廓?

javascript - 如何在 JavaScript 中使用两点坐标来旋转 div?

css - 填充拉伸(stretch)一个 div