我正在尝试为夜间阅读制作一种暗模式切换器,问题是如何将所有黑色文本切换为白色(不同 p 标签和不同 h 标签中的黑色文本都有自己的类,请参见代码片段) 我对彩色文字很好,不需要切换它, 我尝试使用属性选择器,但运气不佳
body.dark-mode [color=black] {
color:white;
function toggleDarkLight() {
var body = document.getElementById("body");
var currentClass = body.className;
body.className = currentClass == "dark-mode" ? "light-mode" : "dark-mode";
}
.three{
color:green;
}
.first{
color:blue;
}
.one {
color:red;
}
.another{
color:black
}
body.dark-mode {
background-color: #111;
}
body.dark-mode button {
background-color: #eee;
color: #111;
}
body.light-mode {
background-color: #eee;
}
body.light-mode button {
background-color: #111;
color: #eee;
}
<body id="body" class="dark-mode">
<h1 class="three">Dark/Light Mode Switcher</h1>
<button type="button" name="dark_light" onclick="toggleDarkLight()" title="Toggle dark/light mode">🌛</button>
<div>
<h1 class="first">title</h1>
<h1 class="some">title 2</h1>
<p class="one">Just press the button above to toggle!</p>
<p class="another"> some text</p>
</div>
</body>
最佳答案
在 css 中没有这样的选择器(并且有充分的理由 - 毕竟它会导致无限反馈循环)。您只需要手动定位每个类 - 或者,如果合理的话,只需使用 body.dark-mode * { color: white; }
将所有颜色都涂成白色 - 然后排除您想要保持不同颜色的元素。
也许你可以使用js。那么这样的事情可能会有所帮助:
https://codepen.io/anon/pen/OdyPJG
document.querySelectorAll("*"),
i=0, ii=allElements.length;
for(i; i<ii; i++){
let element = allElements[i]
if(getComputedStyle(element).color === 'rgb(0, 0, 0)'){
element.classList.add('white')
}
}
关于html - 属性选择器覆盖多个元素的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54347357/