是否可以在 html 中隐藏样式属性,使其仍然有效?我的意思是:
<html style="--color:#1E90FF;">
当我通过 removeAttr 删除属性时,它根本不起作用。我无法通过 CSS 这样操作:
:root {
--color: dodgerblue;
}
因为该值是根据值通过 localStorage 插入的。是否可以使用 jquery 将其粘贴到:root 中而不创建此 style 属性?有什么想法吗?
答案 0 :(得分:2)
如果页面中有“样式”标签,则可以使用“ insertRule”在其中插入CSS规则:
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule
document.getElementsByTagName('style')[0].sheet.insertRule(":root { --color: dodgerblue; }");
您还可以创建一个标签,在其中插入规则:
document.getElementById('trigger').addEventListener('click', function() {
if (!document.getElementById('myCustomStyle')) {
var styleTag = document.createElement('style');
styleTag.id = 'myCustomStyle';
document.head.appendChild(styleTag);
styleTag.sheet.insertRule(":root { --color: dodgerblue; }");
styleTag.sheet.insertRule("p { color: var(--color); }");
}
});
<p>Click the button to insert CSS rules.</p>
<button id="trigger">INSERT</button>
希望这会有所帮助!