修改< style>的innerHTML。元素 [英] Modifying the innerHTML of a <style> element in IE8

查看:154
本文介绍了修改< style>的innerHTML。元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个样式元素,我需要把一些CSS。以下代码适用于Chrome,Safari和FF,但在IE8中失败:

I am creating a style element and I need to put some CSS into it. The below code works in Chrome, Safari and FF, but fails in IE8:

var styleElement = document.createElement("style");

styleElement.type = "text/css";

styleElement.innerHTML = "body{background:red}";

document.head.appendChild(styleElement);

在IE8中,代码在innerHTML部分失败。我尝试过:

In IE8, the code fails when it comes to the innerHTML part. I've tried doing:

var inner = document.createTextNode("body{background:red}");

styleElement.appendChild(inner);

但这也失败了意外调用方法或属性访问。
我正在寻找解决方法或修复。

But this also fails with "Unexpected call to method or property access." I'm looking for a workaround or fix.

推荐答案

使用 .styleSheet.cssText

Use .styleSheet.cssText

注意:与修改个别元素样式相比,这在IE8中似乎非常慢。

NOTE: this seems to be REALLY slow in IE8 compared to modifying individual elements style.

在IE中动态修改样式表有更快的方法吗?

Is there a faster way to modify style sheets dynamically in IE?

这在IE8中很慢:

styleElement.styleSheet.cssText = "body{background:red}";

这在IE8中也很慢(假设要修改的样式对象是head):

This is also slow in IE8 (assumes the style object to be modified is the 1st style element in the head):

document.styleSheets[0].cssText = "body{background:red}";

这在IE8中很快:

document.body.style.background = "red";

这篇关于修改< style>的innerHTML。元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆