javascript - 替换内联 css——并不像看起来那么简单

标签 javascript css

好的,听着。我得到了这样的东西:

<div class="theinsideofclass" style="theinsideofstyle" ...></div>
<div class="theinsideofclass" style="theinsideofstyle" ...></div>
<div class="theinsideofclass" style="theinsideofstyle" ...></div>
<div class="theinsideofclass" style="theinsideofstyle" ...></div>

而且它们是动态变化的(每次都在不同的时间),我对源代码没有任何控制权。

问题是,我只想重写 theinsideofstyle,但我的所有尝试都失败了。我尝试使用 !important; 但它没有成功。它不是应该覆盖内联 css 吗?无论如何,我在这里有什么选择?显然,简单的 JS 在这里帮不了我,因为整个 div 每次都用相同的代码更改/替换。

随心所欲地拍摄,伙计们……也许它会导航找到一些解决方案。

最佳答案

您可以编写一些 JS,在整个页面加载、所有资源加载等情况下执行:

function load() 
{
    var els = document.getElementsByClassName("theinsideofclass");
    for(var i = 0; i < els.length; i++) {
        els[i].removeAttribute("style");
     }
}
window.onload = load;
.theinsideofclass {
  color: green;
  }
<div class="theinsideofclass" style="color: red;">
  My inline style is color: black
</div>
<div class="theinsideofclass" style="color: red;">
  My inline style is color: black
</div>
<div class="theinsideofclass" style="color: red;">
  My inline style is color: black
</div>

如您所见,如果没有 JS,内联样式(字体颜色为红色)通常会覆盖外部 CSS 样式(绿色)。但是,我的 JS 正在从具有 theinsideofclass 类的元素中删除 style 属性,因此您可以使用普通 CSS WITHOUT 使用 进行样式设置!important(我从不使用 !important,除非我用尽所有其他选项)。

关于javascript - 替换内联 css——并不像看起来那么简单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37024358/

相关文章:

javascript - 检查数组中对象中的两个相等值

javascript - 复选框 : Enable button if checkbox checked

css - 如何将 CSS 样式传递给我的 Angular 2 组件?

html - 布局死胡同——表格单元格不断溢出

javascript - jQuery 无法在不同的虚拟主机上运行

Javascript:为什么要使用 indexOf() 来匹配字符串中的值?

javascript - 每次都调用 jQuery ajaxComplete?

CSS 与 Spring MVC 和 JBoss AS 的链接

html - D3 JS Arch,边界有圆圈

html - 表格侧边栏向下移动