如何在JavaScript中将样式属性重置为CSS默认值?

avwztpqn  于 2023-08-09  发布在  Java
关注(0)|答案(5)|浏览(132)

在php生成的页面上,有几个这样的元素:

<td class="defaultTDStyle" style="color:userDefinedCustomColor" id="myTDId"></td>

字符串
所以有一个默认样式,我应用了几个额外的样式来覆盖CSS中定义的样式。
有没有办法从JavaScript中删除这些添加的样式?obj.style.color="default"obj.style.color="auto"似乎不工作。如何从JavaScript将颜色重置为CSS默认值?

d5vmydt9

d5vmydt91#

如果回忆有用的话,obj.style.color=""应该能用……我不知道这是不是对的。

bxjv4tth

bxjv4tth2#

将样式特性值设置为空字符串:

obj.style.color = "";

字符串

enyaitl3

enyaitl33#

新方法:

el.attributeStyleMap.delete('color')

字符串
或清除一切:

el.attributeStyleMap.clear()


但并非所有浏览器都支持此功能。请参阅MDN上的StylePropertyMap以了解更多详细信息和浏览器兼容性。
参见CSS Typed Object ModelWorking with the new CSS Typed Object Model

laik7k3q

laik7k3q4#

可以在覆盖属性样式之前保存它,然后再次应用它。就像这样:

// Get element styling
const element = document.getElementById('someId');
const style = element.getAttribute('style');
const classList = element.classList;
/** Code for overriding element styling goes here **/ 
// Retrieve original styling
const newClassList = element.classList;
for (let item of newClassList) 
    element.classList.remove(item);
for (let item of classList)
    element.classList.add(item);
element.setAttribute('style', style);

字符串

ltqd579y

ltqd579y5#

如果你之前通过JS设置了样式,你可以:

element.style.color = null;

字符串
这将重置样式声明。更多信息:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

相关问题