使用text方法将css规则添加到样式元素在IE中不起作用 [英] Adding css rules with text method to style element does not work in IE

查看:142
本文介绍了使用text方法将css规则添加到样式元素在IE中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它在Firefox和Chrome中运行良好,但在IE8中不起作用。这是html结构:

It works fine in Firefox and Chrome, but does not work in IE8. Here is the html structure:

<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  <script type="text/javascript">
   $(function() {
    // this does not work in IE
    $('<style type="text/css"></style>').text('body {margin: 0;}').appendTo('head');
   });
  </script>
 </head>
 <body>
 </body>
</html>

在IE中这样做的替代方法是什么?

And what' s the alternative to do this in IE?

推荐答案

这在IE7中对我有用:

This is working for me in IE7:

$('<style type="text/css">body {margin: 0;}</style>').appendTo($('head'));

另一种可能更容易阅读的语法:

Another syntax which might be easier to read:

$('head').append('<style type="text/css">body {margin:0;}</style>');

然而,调用 .text(val) .html(val)设置 style 标记的内容将导致抛出异常,因为它们设置 innerHTML DOM属性是只读的。

However, calling either .text(val) or .html(val) to set the contents of the style tag will cause an exception to be thrown because they set the innerHTML DOM property which is read-only.

这是 IE的文档 innerHTML property:

Here is IE's documentation of the innerHTML property:


除了以下内容之外,所有
对象的属性都是可读/写的,对于
,它是只读:COL,COLGROUP,
FRAMESET,HEAD,HTML,STYLE,TABLE,
TBODY,TFOOT,THEAD,TITLE,TR。

The property is read/write for all objects except the following, for which it is read-only: COL, COLGROUP, FRAMESET, HEAD, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR.

这篇关于使用text方法将css规则添加到样式元素在IE中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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