javascript 尝试使用javascript(IE8中的innerHTML)添加样式标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9250386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:03:49  来源:igfitidea点击:

Trying to add style tag using javascript (innerHTML in IE8)

javascriptinternet-explorerinnerhtml

提问by Hakan

This doesn't work in IE8. I think it's the innerHTML that causes the problem. How to solve?

这在 IE8 中不起作用。我认为是导致问题的innerHTML。怎么解决?

// jQuery plugin
(function( $ ){

    $.fn.someThing = function( options ) {  

        var d = document,
            someThingStyles = d.createElement('style');

        someThingStyles.setAttribute('type', 'text/css');
        someThingStyles.innerHTML = " \
        .some_class {overflow:hidden} \
        .some_class > div {width:100%;height:100%;} \
        ";
        d.getElementsByTagName('head')[0].appendChild(someThingStyles);

        });

    };

})( jQuery );

回答by Rob W

jQuery

jQuery

Since you're already using jQuery, use:

由于您已经在使用 jQuery,请使用:

 $('<style type="text/css">' + 
   '.some_class {overflow:hidden}' +
    '.some_class > div {width:100%;height:100%;}' +
    '</style>').appendTo('head');

Pure JavaScript

纯 JavaScript

If you don't want to use jQuery, you have to first append the <style>element, then use the style.styleSheet.cssTextproperty (IE-only!!).

如果您不想使用 jQuery,则必须先附加<style>元素,然后使用style.styleSheet.cssText属性(仅限 IE !!)。

var d = document,
    someThingStyles = d.createElement('style');
d.getElementsByTagName('head')[0].appendChild(someThingStyles);
someThingStyles.setAttribute('type', 'text/css');

someThingStyles.styleSheet.cssText = " \
.some_class {overflow:hidden} \
.some_class > div {width:100%;height:100%;} \
";

回答by kennebec

If you weren'tusing jquery, IE before version 9 writes to a style element by assigning a css string to the styleelement.styleSheet.cssText.

如果您没有使用 jquery,版本 9 之前的 IE 会通过将 css 字符串分配给 styleelement.styleSheet.cssText 来写入样式元素。

Other browsers (including IE9+) let you append text nodes to the element directly.

其他浏览器(包括 IE9+)允许您直接将文本节点附加到元素。

function addStyleElement(css){
  var elem=document.createElement('style');
  if(elem.styleSheet && !elem.sheet)elem.styleSheet.cssText=css;
  else elem.appendChild(document.createTextNode(css));
  document.getElementsByTagName('head')[0].appendChild(elem); 
}

回答by J. K.

You should check out the CSSOM (CSS Object Model) spec - http://dev.w3.org/csswg/cssom/

您应该查看 CSSOM(CSS 对象模型)规范 - http://dev.w3.org/csswg/cssom/

You will probably be interested in the cssTextproperty of CSSRuleobjects - http://dev.w3.org/csswg/cssom/#dom-cssrule-csstext

您可能会对对象的cssText属性感兴趣CSSRule- http://dev.w3.org/csswg/cssom/#dom-cssrule-csstext