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

时间:2015-04-28 14:25:54

标签: 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>

如何使用jQuery删除应用于.containerTitle的样式?

3 个答案:

答案 0 :(得分:5)

有两种选择:

如果您可以删除整个样式表(删除stylelink元素),则会删除该样式表定义的所有规则。

直播示例

$("input").on("click", function() {
  $("style").remove(); // Your selector would be more specific, presumably
});
.red {
  color: red;
}
.green {
  color: green;
}
.blue {
  color: blue;
}
<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">

或者,如果您只需删除一个规则,则可以,但这很痛苦:您浏览styleSheets collection以查找stylesheet object for it,然后找到样式表的cssRules列表中的相关规则(在旧IE上仅称为rules),可能通过查看每个CSSStyleRuleselectorText属性,然后调用{{3}删除它。

// 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;
});

直播示例 (请参阅评论)

$("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;
  });
});
.red {
  color: red;
}
.green {
  color: green;
}
.blue {
  color: blue;
}
<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">

答案 1 :(得分:0)

就个人而言,如果我要做这样的事情,我可能会把我的css放在一个可以轻易更换/移除的身体元素中。 http://jsfiddle.net/oqno5643/已更改为使用html()设置而非append()以删除以前的值:http://jsfiddle.net/oqno5643/1/

HTML

<div id="test">Test text</div>
<input type="button" id="changer" value="Change to Blue">
<span id="styleContainer"></span>

的Javascript

$(document).ready(function(){
    $('#styleContainer').html('<style>#test{ color: red; }</style>');

    $('#changer').on('click', function() {
        $('#styleContainer').html('<style>#test{ color: blue; }</style>');
    });
});

抱歉,打算执行html()而不是append(),但在我的快速演示中忘了。

答案 2 :(得分:-3)

您无法删除样式本身,但可以将其从适用的任何元素中删除。

$('.containerTitle').removeClass('containerTitle');