我有一个网站,其后退/下一步按钮固定在页面的右侧和左侧。它们是单色图标。问题是它们在页面滚动时同时覆盖黑白图像。是否可以设置“ anchor ”或类似的东西,以便当页面到达它时(我猜类似于“粘性”对象的工作方式)我可以更改 div 的颜色?
html(WordPress)
...
<div><?php bnNav_content_nav( 'nav-below' ); ?></div> //puts the back/next buttons on the page
CSS
[class*="navigation"] .nav-previous a,
[class*="navigation"] .nav-next a {
position: fixed;
z-index: 999;
color: #fff;
}
我知道我的代码很难理解,但基本上输出是
post images ...
'anchor' to change the .nav color
post content...
<nav>
<nav id="nav-next"> ... </div>
<nav id="nav-previous"> ... </div>
</nav>
编辑:导航覆盖图像,然后内容位于白色背景上。我希望导航在图像上方时为白色,然后在碰到内容时变为黑色。所以基本上设置一个它会改变的地方
最佳答案
您可以使用 JavaScript 遍历除导航之外的所有元素并检查哪些元素相交,然后将属性放在导航将与您希望导航文本的颜色相交的元素上,然后在每个滚动事件上更新颜色.
var nav = document.querySelector("nav");
var navRect = nav.getBoundingClientRect();
function checkNavColor() {
var allButNav = document.querySelectorAll(":not(nav)");
for (var i = 0; i < allButNav.length; i++) {
var rect1 = allButNav[i].getBoundingClientRect();
var rect2 = navRect;
// By Buu Nguyen (http://stackoverflow.com/a/12067046/4245061)
if (!(rect1.right < rect2.left || rect1.left > rect2.right || rect1.bottom < rect2.top || rect1.top > rect2.bottom)) {
nav.style.color = allButNav[i].getAttribute("data-navcolor");
}
}
}
window.addEventListener("scroll", checkNavColor);
checkNavColor();
body {
height: 200vh;
}
nav {
position: fixed;
}
div {
height: 200px;
}
div:first-child {
background: black;
}
div:nth-child(2) {
background: white;
}
div:last-child {
background: black;
}
<nav>Text which changes color</nav>
<main>
<div data-navcolor="white"></div>
<div data-navcolor="black"></div>
<div data-navcolor="white"></div>
</main>
如果您在代码段中有多个元素并且还使用 HTML 表示非语义内容,这将是一个非常糟糕的解决方案。
如果您希望文本在任何背景下都可见,您可以添加与文本颜色相反的阴影:
body {
height: 200vh;
}
nav {
position: fixed;
/* Add the smallest possible shadow in all directions */
text-shadow: -1px -1px 0 white, 1px -1px 0 white, -1px 1px 0 white, 1px 1px 0 white;
}
div {
height: 200px;
}
div:first-child {
background: black;
}
div:nth-child(2) {
background: white;
}
div:last-child {
background: black;
}
<nav>Text which has a shadow of the opposite color</nav>
<main>
<div></div>
<div></div>
<div></div>
</main>
关于javascript - 在不同的页面位置定位 div 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37099352/