创建动态内联样式表 [英] Create dynamic inline stylesheet

查看:67
本文介绍了创建动态内联样式表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用js和/或jQuery创建动态样式标签的最佳方法是什么?

What is the best way of creating dynamic style tags using js and/or jQuery?

我试过这个:

var style= jQuery('<style>').text('.test{}');

这适用于FF但在IE7中弹出错误对方法或属性访问的意外调用。 / p>

This works in FF but pops an error in IE7 "Unexpected call to method or property access."

var style = document.createElement('style');
style.innerHTML='.test{}';

给出相同的错误。如果我使用 innerHTML innerText ,则无关紧要。奇怪的是它在附加样式标记之前显示错误。

Gives the same error. It doesn't matter if I use innerHTML or innerText. The strange thing is that it shows an error before appending the style tag.

我怀疑 cssText 有什么要的做它,但我不确定如何。

I suspect that cssText has something to do with it, but I'm not sure how.

推荐答案

将文本添加到将被正确呈现的样式表需要一个不同的IE中的语法比其他浏览器。
您可以使用jquery来使用其中一些

Adding text to a stylesheet that will be rendered correctly needs a different syntax in IE than other browsers. You may be able to use some of this with jquery

   document.addStyle= function(str, hoo, med){
     var el= document.createElement('style');
     el.type= "text/css";
     el.media= med || 'screen';
     if(hoo) el.title= hoo;
     if(el.styleSheet) el.styleSheet.cssText= str;//IE only
     else el.appendChild(document.createTextNode(str));
     return document.getElementsByTagName('head')[0].appendChild(el);
    }

这篇关于创建动态内联样式表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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