动态加载css方法 [英] dynamically load css approaches

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

问题描述

我早就知道,您可以使用addRule()和insertRule()动态地将样式规则加载到页面中,具体取决于它是IE还是符合标准的浏览器。但我刚刚发现,在Chrome,一个更通用的(对我来说)方法工作很好:创建一个样式元素,添加一个texnode到任意css文本(它可以是一个css文件的内容),然后,将其添加到文档。您也可以通过从文档中删除该样式节点来删除它。例如,当我发送字符串div {background-color:red;} \\\
p {font-family:georgia;}时,此函数工作正常:

I have long known that you can load style rules into a page dynamically by using addRule() and insertRule(), depending on whether it is IE or a standards compliant browser. But I just discovered that on Chrome, a much more generally-useful (for me) approach works just fine: create a style element, add a texnode to it with arbitrary css text (it could be the contents of a css file), then add that to the document. You can also remove it by removing that style node from the document. For instance this function works fine when I send it the string "div {background-color: red; }\n p {font-family: georgia; }":

var applyCss = function (cssString) {
  var scriptNode = document.createElement('style');
  scriptNode.appendChild(document.createTextNode(cssString));
  document.getElementsByTagName('head')[0].appendChild(scriptNode);
  return scriptNode;
};

虽然我理解在某些情况下以规则为基础的好处,这个快捷方式类似于使用innerHTML而不是使用DOM技术逐个部分构建元素)对于我在很多情况下,如果我可以信赖它工作特别有用。

While I understand the benefits of doing it on a rule basis in some scenarios, this shortcut (which is kind of analogous to using innerHTML instead of building elements part by part using DOM techniques) would be particularly useful to me in a lot of situations if I can count on it working.

是否始终支持?这种方法有什么缺点吗?我特别好奇,因为我从来没有见过这种方法在任何地方建议。

Is it consistently supported? Is there any downside to this approach? I'm particularly curious because I've never seen this approach suggested anywhere.

推荐答案

方法在任何地方提到或建议在很大程度上是因为它是不必要的。而不是不断尝试编辑 style 元素,你应该有一组类,你可以动态添加和删除元素。

The primary reason you wouldn't see this approach mentioned or suggested anywhere is largely because it's unnecessary. Instead of constantly trying to edit style elements, you should have a set of classes that you add and remove from elements dynamically.

根据我的经验,动态添加一个样式元素与文本工作跨浏览器。到目前为止,我没有找到一个浏览器不工作的像:

In my experience, dynamically adding a style element with text works cross browser. So far I haven't found a browser that doesn't work with something like:

//jQuery for brevity
$('<style>p{margin:0}</style>').appendTo('head');

我所需要的只是大集非常具体的样式用于与小书签。否则,我将动态添加样式表:

The only situation I've ever needed this in was for adding a large set of very specific styles for usage with a bookmarklet. Otherwise, I'll dynamically add a stylesheet:

$('<link rel="stylesheet" type="text/css" href="path/to/stylesheet.css />').appendTo('head');


$ b b

但实际上,样式表应该已经存在于HTML中。

But really, stylesheets should already exist within the HTML.

这篇关于动态加载css方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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