使用jQuery从内部样式表中删除样式

Akb*_*sha 0 javascript jquery

<html>
<head>
  <style>
   .containerTitle {
     background-color:silver;
     text-align:center;
     font-family:'Segoe UI';
     font-size:18px;
     font-weight:bold;
     height:30px;
   }
  </style>
</head>
<body>
<div id="a"/>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

如何删除应用于.containerTitlejQuery 的样式?

T.J*_*der 5

有两种选择:

如果您可以删除整个样式表(通过删除styleor link元素),那将删除该样式表定义的所有规则.

实例:

$("input").on("click", function() {
  $("style").remove(); // Your selector would be more specific, presumably
});
Run Code Online (Sandbox Code Playgroud)
.red {
  color: red;
}
.green {
  color: green;
}
.blue {
  color: blue;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="red">red</div>
<div class="green">green</div>
<div class="blue">blue</div>
<input type="button" value="Click to remove the stylesheet">
Run Code Online (Sandbox Code Playgroud)

或者,如果您只需删除一条规则,则可以,但这很痛苦:您查看styleSheets集合以找到它的样式表对象,然后在样式表的cssRules列表中找到相关规则(仅rules在旧IE上调用),可能通过查看每个CSSStyleRuleselectorText属性,然后调用deleteRule将其删除.

// Loop through the stylesheets...
$.each(document.styleSheets, function(_, sheet) {
  // Loop through the rules...
  var keepGoing = true;
  $.each(sheet.cssRules || sheet.rules, function(index, rule) {
    // Is this the rule we want to delete?
    if (rule.selectorText === ".containerTitle") {
      // Yes, do it and stop looping
      sheet.deleteRule(index);
      return keepGoing = false;
    }
  });
  return keepGoing;
});
Run Code Online (Sandbox Code Playgroud)

实例 (见评论):

$("input").on("click", function() {
  // Loop through the stylesheets...
  $.each(document.styleSheets, function(_, sheet) {
    // Loop through the rules...
    var keepGoing = true;
    $.each(sheet.cssRules || sheet.rules, function(index, rule) {
      // Is this the rule we want to delete?
      if (rule.selectorText === ".green") {
        // Yes, do it and stop looping
        sheet.deleteRule(index);
        return keepGoing = false;
      }
    });
    return keepGoing;
  });
});
Run Code Online (Sandbox Code Playgroud)
.red {
  color: red;
}
.green {
  color: green;
}
.blue {
  color: blue;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="red">red</div>
<div class="green">green</div>
<div class="blue">blue</div>
<input type="button" value="Click to remove the green rule">
Run Code Online (Sandbox Code Playgroud)