If an element style property is important (set either trough style=""
or JS), how can one remove it?
如果元素样式属性很重要(通过style =“”或JS设置),如何删除它?
removeProperty()
doesn't work (jsfiddle):
removeProperty()不起作用(jsfiddle):
elem.style.setProperty('background', '#faa', 'important');
elem.style.removeProperty('background'); // doesn't work
(Preferably a frameworkless solution, it only has to work in Chrome.)
(最好是无框架解决方案,它只需要在Chrome中运行。)
1 个解决方案
#1
13
The reason you can't remove the property is because it's a shorthand property.
您无法删除该属性的原因是因为它是一个速记属性。
When you set it, other properties actually get added, but no "background" property, so there's no "background" property to remove.
设置它时,实际上会添加其他属性,但没有“background”属性,因此没有要删除的“background”属性。
In this case, you can unset it like this:
在这种情况下,你可以这样取消设置:
elem.style.removeProperty('background-color');
In general, you'd need to unset every "long-hand" property represented by the shorthand property.
通常,您需要取消设置由速记属性表示的每个“long-hand”属性。
You could also do this to overwrite it:
你也可以这样做来覆盖它:
elem.style.setProperty('background', 'inherit', 'important');
Or you could nuke the entire inline style for the element like this:
或者你可以像这样核对元素的整个内联样式:
elem.style.cssText = '';
#1
13
The reason you can't remove the property is because it's a shorthand property.
您无法删除该属性的原因是因为它是一个速记属性。
When you set it, other properties actually get added, but no "background" property, so there's no "background" property to remove.
设置它时,实际上会添加其他属性,但没有“background”属性,因此没有要删除的“background”属性。
In this case, you can unset it like this:
在这种情况下,你可以这样取消设置:
elem.style.removeProperty('background-color');
In general, you'd need to unset every "long-hand" property represented by the shorthand property.
通常,您需要取消设置由速记属性表示的每个“long-hand”属性。
You could also do this to overwrite it:
你也可以这样做来覆盖它:
elem.style.setProperty('background', 'inherit', 'important');
Or you could nuke the entire inline style for the element like this:
或者你可以像这样核对元素的整个内联样式:
elem.style.cssText = '';