本文介绍了使用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.

这是 innerHTML property:

Here is IE's documentation of the innerHTML property:

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

10-29 23:28