如何删除重要的CSS属性?

Qta*_*tax 7 javascript css google-chrome

如果元素样式属性很重要(设置为低谷style=""或JS),如何删除它?

removeProperty()不起作用(jsfiddle):

elem.style.setProperty('background', '#faa', 'important');
elem.style.removeProperty('background'); // doesn't work
Run Code Online (Sandbox Code Playgroud)

(最好是无框架解决方案,它只需要在Chrome中运行.)

Dag*_*bit 13

您无法删除该属性的原因是因为它是一个速记属性.

设置它时,实际上会添加其他属性,但没有"background"属性,因此没有要删除的"background"属性.

在这种情况下,您可以像这样取消设置:

elem.style.removeProperty('background-color');
Run Code Online (Sandbox Code Playgroud)

通常,您需要取消设置由速记属性表示的每个"long-hand"属性.


你也可以这样做来覆盖它:

elem.style.setProperty('background', 'inherit', 'important');
Run Code Online (Sandbox Code Playgroud)

或者你可以像这样核对元素的整个内联样式:

elem.style.cssText = '';
Run Code Online (Sandbox Code Playgroud)

  • 有趣的是,如果`removeProperty('background')` 没有设置为`important`,它确实可以工作。 (2认同)