html - 属性选择器覆盖多个元素的类

标签 html css

我正在尝试为夜间阅读制作一种暗模式切换器,问题是如何将所有黑色文本切换为白色(不同 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/

相关文章:

html - margin 使用错误 div 的 css 创建的空间

javascript - 如何判断 Google Analytics 是否已加载

html - 将第二行链接与第一行的开头对齐

javascript - 动态下拉菜单样式选择器

css - 在 css 中使用自定义字体时出错

css - PrimeNG Accordion 无法正常工作和显示

css - 如何让 td 表格单元格跨越表格的整个宽度?

html - 选择时更改输入字段的颜色

javascript - 为什么 Flask 中的 URL 重定向在控制台中有效,但现在在实际的 Web 应用程序中有效?

图像的 Css UL LI 对齐