使用Javascript将CSS样式表作为字符串插入 [英] Inject CSS stylesheet as string using Javascript

查看:110
本文介绍了使用Javascript将CSS样式表作为字符串插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Chrome扩展程序,我希望用户能够添加自己的CSS样式,以更改扩展程序网页(而不是网页)的外观。我研究过使用 document.stylesheets ,但它似乎想要的规则分裂,并不会让你注入一个完整的样式表。有没有一个解决方案,让我使用一个字符串来创建一个新的样式表在页面上?

I'm developing a Chrome extension, and I'd like users to be able to add their own CSS styles to change the appearance of the extension's pages (not web pages). I've looked into using document.stylesheets, but it seems like it wants the rules to be split up, and won't let you inject a complete stylesheet. Is there a solution that would let me use a string to create a new stylesheet on a page?

我目前不使用jQuery或类似的,所以纯Javascript解决方案

I'm currently not using jQuery or similar, so pure Javascript solutions would be preferable.

推荐答案

您可以创建一个样式元素并将字符串添加为innerHTML。这样的东西:

You could create a style element and add the string as the innerHTML. Something like this:

function addStyleString(str) {
    var node = document.createElement('style');
    node.innerHTML = str;
    document.body.appendChild(node);
}

addStyleString('body { color: red }');
addStyleString('body { background: silver }');
// This way allows you to add CSS in multiple passes

strong>重要编辑:请注意,IE9及以下版本只允许最多32个样式表,因此在使用上述代码段时请小心,在IE10中数字增加到4095)

(Important edit: Be aware that IE9 and below only allows up to 32 stylesheets, so watch out when using the above snippet. The number was increased to 4095 in IE10.)

如果当用户添加新CSS时,要删除旧样式并添加新样式,则可以将该函数向上切换,以便引用一个节点。 p>

If, when a user adds new CSS, you want to remove the old styles and add the new, you can switch the function up so you have a reference to one node.

(function() {
    var node = document.createElement('style');
    document.body.appendChild(node);
    window.addStyleString = function(str) {
        node.innerHTML = str;
    }
}());

addStyleString('body { color: red }');
addStyleString('body { background: silver }');
// This way will remove the old style when the new one is added

这篇关于使用Javascript将CSS样式表作为字符串插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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