我正在尝试向我的网站添加粘性导航,当它滚动到不同的部分时会发生变化。当滚动到带有 .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/