IE在动态增加CSS时有bug

关键词:

IE, styleSheet.cssText, document.createElement('style')

用javascript脚本动态调整网页的CSS一般是这么做的
1.创建 style标签
2.填充css规则
3.插入head节点

这些都没有问题,网上查到的都是这么干的。但是在IE下,却有数量限制,如果不断重复上述1-3步,会发现最终IE会报错“Error: 无效的过程调用或参数”。

具体可以用这个代码来测试:

<html>
<head>

<script>

function add()
{

  var st = document.createElement('style');
  st.setAttribute('type','text/css');

  document.getElementsByTagName('head')[0].appendChild(st);

  st.styleSheet.cssText = ' body { background-color:red; } ';

}

</script>

</head>

<body>

<input type="button" value="Add Css" onclick="add()" />

</body>
</html>

不断点Add Css按钮,当点到60多下的时候就会脚本出错,在实际应用中根据css规则数量多少,可能不需要这么久就会出错。

测试了几个浏览器,只有IE有这个问题

当然有些浏览器没有styleSheet.cssText属性。需要用类似这样的代码:

var cssText = 'body{background-color:red;}';
var st = document.createElement('style');
st.setAttribute('type','text/css');
document.getElementsByTagName('head')[0].appendChild(st);

if(st.styleSheet){
                st.styleSheet.cssText = cssText;
}else{
                st.appendChild(document.createTextNode(cssText));
}

如何绕开IE的这个古怪bug?

很简单,减少<style>标签的数量。
如果确实需要不断动态更新CSS怎么办?
也有办法,只用一个style标签来添加动态css规则,
每次添加前,把之前的<style>标签内容取出来,并删除该<style>标签,再把老的css规则和新的规则一起生成一个新的<style>插入head节点。

提醒,为了兼容大部分浏览器,一定要把style插入head节点,不要插入<body>节点中。

2 条评论 »

  1. Ray said,

    2008/7/3 @ 12:26

    顶下,米胖是我见过的国内用户体验最好的web2.0网站

  2. Nukq said,

    2008/7/3 @ 13:46

    谢谢Ray.
    这个是我在做米胖的自定义空间模板的时候碰到的问题。

RSS feed for comments on this post · TrackBack URI

发表看法

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word