【问题标题】:How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?如何使用 javascript 擦除所有内联样式并仅保留 css 样式表中指定的样式?
【发布时间】:2010-11-16 19:30:17
【问题描述】:

如果我的 html 中有以下内容:

<div style="height:300px; width:300px; background-color:#ffffff;"></div>

这在我的 css 样式表中:

div {
    width:100px;
    height:100px;
    background-color:#000000;
}

有没有什么方法可以用 javascript/jquery 删除所有的内联样式,只保留 css 样式表指定的样式?

【问题讨论】:

    标签: javascript jquery css inline


    【解决方案1】:

    $('div').attr('style', '');

    $('div').removeAttr('style');(来自Andres's Answer

    要缩小一点,试试这个:

    $('div[style]').removeAttr('style');

    这应该会加快速度,因为它会检查 div 是否具有样式属性。

    无论哪种方式,如果您有大量 div,这可能需要一些时间来处理,因此您可能需要考虑 javascript 以外的其他方法。

    【讨论】:

    • 如果它必须删除样式属性,它也必须寻找它,所以最后一个解决方案似乎只是让代码更脏恕我直言。最好的当然是只选择您需要删除样式的元素,可能通过 ID。
    • 这只会针对 div。如果您想针对所有内容怎么办?
    • 顺便说一句,使用空字符串作为第二个值调用 .css() 将仅从内联样式中删除命名值,例如 $('div').css('display', ' ');将仅删除内联显示属性(如果已设置)。
    • @streetlight 使用$('*').removeAttr('style') 定位所有内容。
    • 不,实际上第二个应该快一点,因为如果 JQuery 有任何意义,那么它将使用标准的 removeattribute。此外,您忘记了循环通过更多 DOM 元素的巨大低效开销,这使得第二种方法比第一种方法更快。
    【解决方案2】:
    $('div').removeAttr('style');
    

    【讨论】:

    • 这比做 attr('style', '') 效率高吗?
    • with $('div').attr('style', '');
      with $('div').removeAttr('style');
      更干净
    • 可能,因为它没有将其设置为空值,但无论哪种方式,您都会得到很长的处理时间,因为它必须遍历正文中的每个 div。
    • 是的,很明显,应该改成ID $("#id") 或者class $(".classDivs)
    【解决方案3】:

    您也可以尝试将样式表中的 css 列为 !important

    【讨论】:

    • 虽然这可行,但使用 !important 覆盖内联样式以删除它们是一种糟糕的做法
    【解决方案4】:

    我使用了$('div').attr('style', ''); 技术,但它在 IE8 中不起作用。

    我使用alert() 输出了样式属性,它没有去除内联样式。

    .removeAttr 最终在 IE8 中成功了。

    【讨论】:

      【解决方案5】:

      纯 JavaScript:

      你不需要 jQuery 来做这样的小事。只需使用.removeAttribute() 方法即可。

      假设您只针对单个元素,您可以轻松使用以下内容:(example)

      document.querySelector('#target').removeAttribute('style');
      

      如果您要定位多个元素,只需遍历选定的元素集合:(example)

      var target = document.querySelectorAll('div');
      Array.prototype.forEach.call(target, function(element){
          element.removeAttribute('style');
      });
      

      Array.prototype.forEach() - IE9 及以上/.querySelectorAll() - IE 8(部分)IE9 及以上。

      【讨论】:

      • Array.prototype.forEach.call 的替代方案是相当受支持的 splat 运算符,它节省了一行:[... document.querySelectorAll('div')].forEach(div =&gt; div.removeAttribute('style'))
      【解决方案6】:

      这可以分两步完成:

      1:通过标记名、id、类等选择要更改的元素。

      var element = document.getElementsByTagName('h2')[0];

      1. 移除样式属性

      element.removeAttribute('style');

      【讨论】:

        【解决方案7】:

        如果您只需要清空元素的style,那么:
        element.style.cssText = null;
        这应该会很好。希望对您有所帮助!

        【讨论】:

        • 如果试图“清空”一个元素的单个样式属性,类似的逻辑似乎适用:element.style.display = null; - 这就是我需要的:D
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-01-15
        • 2013-12-19
        • 2018-04-29
        • 1970-01-01
        • 2013-01-05
        • 2021-08-04
        • 2018-05-04
        相关资源
        最近更新 更多