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

查看:12
本文介绍了将带有文本方法的 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 属性:

该属性对所有人都是可读/可写的除以下对象外,对于它是只读的:COL、COLGROUP、框架、头部、HTML、样式、表格、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.

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

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