【问题标题】:How to remove css from DOM如何从 DOM 中删除 css
【发布时间】:2016-09-11 00:14:17
【问题描述】:

我有一个允许用户在运行时更改主题的应用程序。

在加载新的 CSS 之前,此代码会删除旧的 CSS:

jQuery('head > link').each(function () {
            if (this.href.includes('styles/kendo.')) {
                DOM.removeNode(this);
            }
        });

这对我来说看起来不错,但是当它运行时,某些东西会损坏(不确定是什么)并且后来 CSS 无法正确加载。

如果我注释掉这段代码,那么 CSS 就会正常加载。对我来说毫无意义。

也许有一种完全不同的方法可以更好地从 DOM 中删除 CSS?

【问题讨论】:

  • 您很可能会抛出一些错误,.href.includes 未定义。检查您的控制台。 DOM 也可能是未定义的。
  • 不,根本没有错误信息。
  • 你确定吗?那什么是 DOM?你确定 .includes 可用,并且你所有的链接标签都有 href 属性吗?
  • 使用 $(this).remove() 会是更好的方法,因为您已经在使用 jQuery。
  • @GregGum 我刚刚做了 :)

标签: css


【解决方案1】:

在代码中一切看起来都很好,直到

jQuery('head > link').each(function () {
            if (this.href.includes('styles/kendo.')) {

下一行 DOM.removeNode(this); 应该删除 HTML 元素,即 this 使用 DOM.removeNode 方法,它不是一个内置对象,因此我们不知道它是如何工作的,可能你的应用程序中的一个库可能拥有该对象,因此您可能需要检查其文档。

如果我们的任务是从 DOM 中删除特定的 HTML 链接元素,我们可以使用 jQuery $.remove() 方法比这更好,

jQuery('head > link').each(function () {
            if (this.href.includes('styles/kendo.')) {
                $( this ).remove();

【讨论】:

    【解决方案2】:

    你试过document.styleSheets[i].disabled = true;吗?

    这适用于纯 JS(无 jQuery):

    for (var i = 0; i < document.styleSheets.length; i++) {
      if (document.styleSheets[i].href.includes('styles/kendo.')) {
        document.styleSheets[i].disabled = true;
      }  
    }
    

    在普通 JS 中的另一种方法是使用 forEach:

    [].forEach.call(document.styleSheets, function(element, index, array) {
      if (array[index].href.includes('localhost')) {
        document.styleSheets[index].disabled = true;
      }
    });
    

    (为什么.forEach[]开头,使用.call解释here

    这将是 jQuery 版本:

    jQuery(document.styleSheets).each(function(i) {
      if (document.styleSheets[i].href.includes('styles/kendo.')) {
        document.styleSheets[i].disabled = true;
      }  
    });
    

    这里有一些关于document.styleSheet等的参考资料:

    【讨论】:

    • 非常感谢您的详细解答。
    猜你喜欢
    • 2013-10-20
    • 1970-01-01
    • 2015-01-29
    • 2023-01-30
    • 2021-11-22
    • 1970-01-01
    • 2015-03-26
    • 2012-09-29
    • 2014-07-18
    相关资源
    最近更新 更多