javascript - style.styleSheet.cssText 在 IE 9 上不起作用

标签 javascript jquery internet-explorer

类似于以下功能的最佳方法是什么,

适用于所有浏览器及其任何版本,特别是 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/

相关文章:

javascript - 如何附加到 javascript 中的现有正则表达式?

javascript - 如何将移动菜单的内容居中?

javascript - 如何确定 Raphael text() 的准确高度?

css - IE 加载的样式表不超过 30 个(drupal)?

php - 溢出-x/y 在 IE 中不起作用

javascript - 如何让 jquery 堆栈/协同工作

javascript - 搜索多个值的本地存储历史记录

jquery - 收获jquery-选择而不选择?

jquery - 当页面加载和单击链接时触发 jQuery 函数?

internet-explorer - 使用 VBA 自动化 IE - 单击 Javascript 链接(无 anchor 标记)