简体   繁体   English

删除带有 !important 属性的 CSS 规则

[英]Remove CSS rule with !important property

In order to "null" pseudo elements content I use:为了“空”伪元素内容,我使用:

  var rule = document.styleSheets[0].insertRule('.video-js * .vjs-icon-placeholder:before {content: " "!important;}', 0);

I works only if ".important" property specified.我仅在指定“.important”属性时才工作。 In some situation I need to restore original pseudo elements content: I tried: document.styleSheets[0].deleteRule(rule) ;在某些情况下,我需要恢复原始伪元素内容:我尝试过: document.styleSheets[0].deleteRule(rule) That doesn't work.那是行不通的。 Is there is a way to restore original content?有没有办法恢复原始内容?

It doesn't work, because when you remove the rule, it removes the content from the HTML,它不起作用,因为当您删除规则时,它会从 HTML 中删除content

I believe the best method would be to get the content first and then reassign.我相信最好的方法是先获取content然后重新分配。

var prev = window.getComputedStyle(
    document.querySelector('..vjs-icon-placeholder'), ':before'
).getPropertyValue('content')

let prevContent = prev.substring(1,prev.length-1) //to remove the quotes from start and end.

var rule = document.styleSheets[0].insertRule('.video-js * .vjs-icon-placeholder:before {content: " "!important;}', 0);

Now wherever you decide to revert back to previous content.现在,无论您决定恢复到以前的内容。

var rule = document.styleSheets[0].insertRule('.video-js * .vjs-icon-placeholder:before {content: '+prevContent+'!important;}', 0);

Just add another class to the element that sets the content to another value.只需将另一个 class 添加到将内容设置为另一个值的元素。

 document.querySelector("button").addEventListener("click", function(e){ document.querySelector(".vjs-icon-placeholder").classList.toggle("nocontent"); });
 .vjs-icon-placeholder:before{ content: "This is some before text"; display: block; color: dodgerblue; }.vjs-icon-placeholder.nocontent:before { content: " "; }
 <div class="vjs-icon-placeholder"> This is a div. </div> <button> Toggle Content </button>

If all video-js elements have a common ancestor (you can use the body for this purpose), you can toggle the nocontent class just on that ancestor instead, ie #ancestor.nocontent.video-js *.vjs-icon-placeholder:before{content: " "} and document.querySelector("#ancestor").classList.toggle("nocontent") .如果所有 video-js 元素都有一个共同的祖先(您可以为此目的使用正文),则可以在该祖先上切换 nocontent class,即#ancestor.nocontent.video-js *.vjs-icon-placeholder:before{content: " "}document.querySelector("#ancestor").classList.toggle("nocontent")

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

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