类似于以下功能的最佳方法是什么,
适用于所有浏览器及其任何版本,特别是 IE。
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
css = "some style here"
style.type = 'text/css';
if (style.styleSheet){
#Problem here: This is works for IE8 and below BUT not in higher version.
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
最佳答案
如果没有 css.styleSheet 对象,也许可以尝试将 css 直接加载到 header 中。
没有时间测试,但我认为它应该有效。如果您有任何疑问,请询问。 :)
<script type="text/javascript">
function appendStyle(styles) {
var css = document.createElement('style');
css.type = 'text/css';
if (css.styleSheet) css.styleSheet.cssText = styles;
else css.appendChild(document.createTextNode(styles));
document.getElementsByTagName("head")[0].appendChild(css);
}
var styles = '#header { color: white }';
window.onload = function() { appendStyle(styles) };
</script>
关于javascript - style.styleSheet.cssText 在 IE 9 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55607065/