在 IE6 中运行时添加 CSS 规则 - 对象不支持此属性或方法

Add CSS rules at runtime in IE6 - Object doesn't support this property or method

本文关键字:不支持 对象 属性 方法 规则 IE6 运行时 添加 CSS      更新时间:2023-09-26

试图让我的网站在IE6中运行,但在我需要做的一些运行时css事情上遇到了问题。

我已经尝试了这两种方法:

$.rule('#post'+ i + '{ visibility:hidden;}').appendTo('style');

-

var postStyle = document.createElement('style');
postStyle.type = 'text/css';    
postStyle.innerHTML = '#post'+ i + '{ visibility:hidden;}';
document.getElementsByTagName('head'[0].appendChild(postStyle);

适用于其他浏览器,但不适用于 IE。我收到此错误:

"对象不支持此属性或方法"

有什么想法吗?

在IE中,你必须这样做:

postStyle.styleSheet.cssText = whatever;

我通常使用try/catch设置来完成此操作。

$('head').append($('<style/>', { id: "replaced-colors" }));
try {
  $('#replaced-colors').html(replaced);
}
catch (_ie) {
  $('#replaced-colors')[0].styleSheet.cssText = replaced;
}

作为一个现实生活中的例子。