简体   繁体   English

如何禁用和启用css规则

[英]How to disable and enable css rule

For example if i have 例如,如果我有

<style type='text/css' id='divcolorgreen'>
    div{
        color: green;
    }
</style>

I can disable the css rule using 3 ways 我可以使用3种方法禁用css规则

  • removing the style element (reappend it to reenable) 删除样式元素(重新启用它以重新启用)
  • modifying it's inner html 修改它的内部HTML
  • add the inline rule one by one to each elements (better using jquery) 逐行添加内联规则到每个元素(更好地使用jquery)

Is there any easier way to disable/remove the css rule? 有没有更简单的方法来禁用/删除css规则?

This is the purpose of classes. 这是课程的目的。 By assigning a class eg. 通过分配一个类,例如。 to the <body> tag, you get the same functionality: <body>标签,您将获得相同的功能:

<style type='text/css' id='divcolorgreen'>
    body.divcolorgreen div{
        color: green;
    }
</style>

And then if <body> looks like this: 如果<body>看起来像这样:

<body class="divcolorgreen">
    ...
</body>

the rule is applied. 该规则适用。 To disable the rule, remove the mentioned class: 要禁用该规则,请删除上述类:

<body>
    ...
</body>

OK, so you are trying to change the color of all divs on a page. 好的,所以你试图改变页面上所有div的颜色。

jQuery has .css() which lets you set the style of all elements that match the selector. jQuery有.css() ,它允许您设置与选择器匹配的所有元素的样式。 In your case, it's just div . 在你的情况下,它只是div

To set: 设置:

$('div').css('color', 'yellow');

To remove: 去除:

$('div').css('color', '');

If you don't want to use jQuery, the idea is the same: 如果你不想使用jQuery,那么想法是一样的:

document.getElementsByTagName('div') gives you all divs on the page. document.getElementsByTagName('div')为您提供页面上的所有div。 You can loop through them and change their style by elem.style.color="yellow"; 你可以通过elem.style.color="yellow";循环遍历它们并改变它们的风格elem.style.color="yellow";

1 you can do this by jquery css( propertyName , value ) api but according to me the easier way because if there is many style like you have set the font ,color ,height,...the second method is easier and lot more time saving 1你可以通过jquery css( propertyName , value ) api做到这一点,但根据我的更简单的方法,因为如果有很多样式,你已经设置了字体,颜色,高度......第二种方法更容易,更多的时间保存

 $("div").css("color", "yellow")

2 you can do this by removeClass('someClass'); 2你可以通过removeClass('someClass');来做到这一点removeClass('someClass'); and addClass('someClass'); addClass('someClass');

for example, use a jQuery selector to target the division element with the class "some" 例如,使用jQuery选择器以“some”类来定位除法元素

html HTML

<div class="some" ></div>

css CSS

.some{ color: green; }

jquery jQuery的

if you want to add another class can use the addClass 如果要添加另一个类可以使用addClass

$(".some").click( function(){
   $(this).addClass('someClass');
});

If you would like to remove the class, use jQuery's removeClass method: 如果要删除该类,请使用jQuery的removeClass方法:

$(".some").click( function(){
   $(this).removeClass('someClass');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM