---
title: "innerHTML插入<style>元素"
author: "sailinglee"
date: "2014-09-05T18:37:20Z"
tags: []
categories: ["Web前端"]
slug: "innerhtml-style"
draft: false
lastmod: "2014-09-05T18:38:16Z"
id: 2113813
url: "https://sailinglee.iteye.com/blog/2113813"
---

通过innerHTML写入&lt;style&gt;元素没有得到浏览器很好的支持，IE9、Opear 9、Chrome高版本和Firefox高版本支持以直观的方式通过innerHTML插入&lt;style&gt;元素，例如：

 

```
div.innerHTML = "<style type=\"text/css\">body {background-color: red;}</style>";
```

 

 

在IE6和IE7中会忽略这个&lt;style&gt;元素。在IE中，&lt;style&gt;也是一个作用域外元素，因此必须想下面这样给它前置一个作用域元素：

 

```
div.innerHTML = "_<style type=\"text/css\">body {background-color: red;}</style>"
div.removeChild(div.firstChild);
```

 

 

低版本的Safari和Chrome则会因为没有将这个&lt;style&gt;元素添加到&lt;head&gt;元素而继续忽略它。如果想在所有浏览器中成功插入&lt;style&gt;元素，就必须想下面这样：

 

```
//针对低版本IE
div.innerHTML = "_<style type=\"text/css\">body{background-color: red;}</style>"
div.removeChild(div.firstChild);
//针对低版本Safari和Chrome
document.getElementsByTagName("head")[0].appendChild(div.firstChild);
```

 

 

在新创建的&lt;style&gt;元素添加到&lt;head&gt;后，低版本的Safari和Chrome会应用新样式。

转自:[http://www.w3cmm.com/dom/innerhtml-style.html](http://www.w3cmm.com/dom/innerhtml-style.html)