【问题标题】:Search and replace legacy background color搜索和替换旧版背景颜色
【发布时间】:2019-01-14 16:21:46
【问题描述】:

我正在使用一些旧的 HTML 和 CSS...

代码如下所示:

<html>
<head>
<style>
table.highlight {
    BACKGROUND: yellow;
}
</style>
</head>
<table class="highlight"><tr><td>test</td></tr></table>
</html>

假设 DOM 代码是只读的,并且唯一的解决方法是在 DOM 加载 之后运行的代码 sn-p,如何寻找这些“黄色”颜色并替换它们?

我尝试查找&lt;table&gt;.style.BACKGROUND&lt;table&gt;.style.background&lt;table&gt;.style.backgroundColor 无济于事,但颜色在网络浏览器中正确显示。

当我回显&lt;table&gt;.style 的内容时,黄色不会出现在任何地方。有没有办法访问这些旧的、遗留的 CSS 组件?

我可以通过设置&lt;table&gt;.style.backgroundColor 成功更改颜色,但我无法找到yellow 一开始的位置。所有读取 CSS 的尝试都返回空白。

我正在 Google Chrome 和 Firefox 中进行测试。两者都返回undefined""

【问题讨论】:

    标签: javascript html css legacy


    【解决方案1】:

    你可以使用getComputedStyle

    [...document.querySelectorAll('table')].forEach(e => {
      // if the background-color is yellow then change it to red
      if (getComputedStyle(e)['background-color'] === 'rgb(255, 255, 0)') 
        e.style.backgroundColor = 'red'
    })
    <html>
    
    <head>
      <style>
        table.highlight {
          BACKGROUND: yellow;
        }
        
        table.highlight2 {
          BACKGROUND: green;
        }
      </style>
    </head>
    <table class="highlight">
      <tr>
        <td>test</td>
      </tr>
    </table>
    <table class="highlight">
      <tr>
        <td>test</td>
      </tr>
    </table>
    <table class="highlight2">
      <tr>
        <td>test</td>
      </tr>
    </table>
    
    </html>

    【讨论】:

      【解决方案2】:

      你不能只使用querySelectorAll 定位所有元素然后处理它们吗?

      如果您要向页面添加脚本并且需要等到 DOM 加载完毕,请将脚本添加到 &lt;/body> 之前。但这也可以在浏览器控制台中运行。

      const yellow = document.querySelectorAll('table.highlight');
      
      // Example: wait 1s and change the yellow tables to blue
      setTimeout(() => yellow.forEach(el => el.style.background = 'blue'), 1000);
      table.highlight { background: yellow; }
      <table class="highlight"><tr><td>test1</td></tr></table>
      <table><tr><td>test2</td></tr></table>
      <table class="highlight"><tr><td>test3</td></tr></table>

      【讨论】:

      • document.querySelectorAll('table.highlight') 比仅循环遍历所有表要好一些。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2017-10-29
      • 2013-10-10
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2016-02-18
      相关资源
      最近更新 更多