目前,我设置了一个页面,当向下滚动时,菜单的颜色会发生变化以弥补背景 - 所以在白色背景上,文字会变黑,反之亦然。
我想将文字更改为徽标,以便在白色背景上标识为黑色;使用图像LOGOBLACK.png,反之亦然,使用LOGOWHITE.png。
这是index.html中的菜单:
<nav id="menu" class="hidden">
<ul>
<li class="go-home">
<a href="index.html"><img src="images/LOGOBLACK.png"></a>
</li>
</ul>
以下是我之前使用的javascript代码:
function updateMenuColor() {
var t = Math.max(window.scrollY, 0) + 50,
e = t - y;
setScrollUp(0 >= e), y = t;
for (var i = document.getElementsByTagName("section"), n = document.body.getBoundingClientRect(), s = 0; s < i.length; s++) {
var a = i[s],
o = a.getBoundingClientRect(),
r = o.top - n.top,
l = o.bottom - n.top;
if (y > r && l > y) {
var c = a.classList.contains("white");
c && !$menuIsWhite ? (switchMenuToWhite(), $menuIsWhite = !0) : !c && $menuIsWhite && (switchMenuToBlack(), $menuIsWhite = !1);
var h = a.classList.contains("text");
h && !$menuIsFaded ? (fadeMenuIn(), $menuIsFaded = !0) : !h && $menuIsFaded && (fadeMenuOut(), $menuIsFaded = !1)
}
}
}
function switchMenuToWhite() {
document.body.classList.add("white")
}
function switchMenuToBlack() {
document.body.classList.remove("white")
}
我无法理解的是如何用文字替代徽标。任何类型的评论总是受到赞赏。
提前感谢您的帮助!
答案 0 :(得分:2)
之前的解决方案是通过添加和删除正文中的类来实现的。没有纯css解决方案来更改徽标的src属性,除非你想要两个img标签并在两者之间切换。这个解决方案只是找到我们想要更改的img-tag,并将它的src属性更改为新的url:
document.getElementsByClassName("go-home")[0].getElementsByTagName('img')[0].src = "/images/LOGOWHITE.png";
另一种解决方案是拥有两个img-tag,每个版本一个,并切换它们。您可以保留当前的javascript代码,但需要添加以下css,并稍微更改一下html:
/* Hide white logo on white background */
body.white .logowhite {
display: none;
}
/* Hide black logo on non-white (black) background */
body:not(.white) .logoblack {
display: none;
}
<a href="index.html">
<img class="logoblack" src="images/LOGOBLACK.png">
<img class="logowhite" src="images/LOGOWHITE.png">
</a>
function togglewhite() {
if (document.body.classList.contains("white")) {
console.log("a");
document.body.classList.remove("white");
} else {
console.log("b");
document.body.classList.add("white");
}
}
&#13;
/* This is not necessary; it is just for easier viewing what happens */
img {
width: 100px;
height: 100px;
}
.logoblack {
background: black;
}
.logowhite {
background: gray;
}
/* This is necessary */
/* Hide white logo on white background */
body.white .logowhite {
display: none;
}
/* Hide black logo on non-white (black) background */
body:not(.white) .logoblack {
display: none;
}
&#13;
<nav id="menu" class="hidden">
<ul>
<li class="go-home">
<a href="index.html">
<img class="logoblack" src="images/LOGOBLACK.png">
<img class="logowhite" src="images/LOGOWHITE.png">
</a>
</li>
</ul>
</nav>
<input type="button" value="Toggle white" onclick="togglewhite()">
&#13;