是否可以在html中隐藏样式属性使其仍然有效?我的意思是:
<html style="--color:#1E90FF;">
当我通过removeAttr删除属性时,它根本不起作用。我不能通过这种方式通过CSS做到这一点:
:root {
--color: dodgerblue;
}
因为值是根据值通过localStorage插入的。有没有办法用jquery将它粘贴到:root而不创建这个样式属性?有任何想法吗?
是否可以在html中隐藏样式属性使其仍然有效?我的意思是:
<html style="--color:#1E90FF;">
当我通过removeAttr删除属性时,它根本不起作用。我不能通过这种方式通过CSS做到这一点:
:root {
--color: dodgerblue;
}
因为值是根据值通过localStorage插入的。有没有办法用jquery将它粘贴到:root而不创建这个样式属性?有任何想法吗?
如果您的页面中有“样式”标签,则可以使用“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>
希望这可以帮助!