简体   繁体   English

如何禁用CSS规则?

[英]How do I disable a CSS rule?

I have the following CSS rule 我有以下CSS规则

#class {
    margin: 4px 5px 6px 7px;
    color: red;
}

What I usualy do is 我通常要做的是

document.getElementById('class').style.margin= '0px';

Then after doing that to reset I go the same step 然后在执行重置后,我执行相同的步骤

document.getElementById('class').style.margin= '4px 5px 6px 7px';

How do I disable the margin using JavaScript\\JQuery instead of changing the value to 0 then reset it to 4px 5px 6px 7px 如何使用JavaScript \\ JQuery 禁用边距, 而不是将值更改为0然后将其重置为4px 5px 6px 7px

Can you make a second class and just add/remove it from your elements? 您可以进行第二堂课,而只是从您的元素中添加/删除它吗?

.margin {
    margin: 4px 5px 6px 7px;
    color: red;
}
.noMargin {
    margin: 0px
    color: red;
}

document.getElementById("class").classList.add('margin');    
document.getElementById("class").classList.remove('noMargin');

document.getElementById("class").classList.add('noMargin');
document.getElementById("class").classList.remove('margin');

The easiest solution here is to use classes, and use jquery or javascript to change the class of the element whenever you want different behavior as on button click in the example I have shown below. 这里最简单的解决方案是使用类,并在每次显示按钮时单击按钮单击时使用jquery或javascript更改元素的类,例如下面显示的示例。

 $("#add").click(function() { $("#exd").addClass('margin'); $("#exd").removeClass('no-margin'); }); $("#rem").click(function() { $("#exd").removeClass('margin'); $("#exd").addClass('no-margin'); }); 
 .no-margin { margin: 0px; } .margin { margin: 15px 15px 15px 15px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="exd">Example Div</div> <button id="add">Add margin</button> <button id="rem">Remove margin</button> 

Hope this is clear. 希望这很清楚。

A slight alteration to Scath's answer 对Scath答案的稍作改动

.margin {
    margin: 4px 5px 6px 7px;
    color: red;
}
.margin.noMargin {
    margin: 0px;
}

Then all you have to do is add/remove the noMargin class. 然后,您要做的就是添加/删除noMargin类。 More specific css rules take precedence. 更具体的CSS规则优先。

The other answers are good, just wanted to share another way of doing this. 其他答案很好,只是想分享另一种方法。 You can keep your base CSS style rule: 您可以保留基本的CSS样式规则:

#class {
    margin: 4px 5px 6px 7px;
    color: red;
}

And then add a noMargin class as others have suggested: 然后像其他人建议的那样添加一个noMargin类:

.noMargin {
    margin: 0; !important
}

And then, use toggleClass to switch it on/off: 然后,使用toggleClass将其打开/关闭:

document.getElementById('class').classList.toggleClass('noMargin');

The benefit here is that A) only one line of code to on/off the margin, B) only one extra CSS rule, and C) don't have to worry about whether the margin is currently on or off before switching it. 这样做的好处是A)仅需一行代码即可打开/关闭页边空白,B)仅需一条额外的CSS规则,C)不必担心在切换页边空白时当前是打开还是关闭。

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

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