使用 JavaScript 将 CSS 添加到 <head>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3922139/
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-08-23 06:39:07  来源:igfitidea点击:

Add CSS to <head> with JavaScript?

javascripthtmlcss

提问by Timo Huovinen

Is there a way to add css from a string in the javascript file to the head of a document with javascript?

有没有办法将 css 从 javascript 文件中的字符串添加到带有 javascript 的文档的头部?

Let's say we have a webpage, which has a lightbox script, this script requires a css file to function.

假设我们有一个网页,它有一个灯箱脚本,这个脚本需要一个 css 文件才能运行。

Now adding this css file with <link>will make the css file download even for people that don't have js enabled.

现在添加这个 css 文件,<link>即使对于没有启用 js 的人也可以下载 css 文件。

I know that I can dynamically load the css file with the script, but that also means that there will be 2 http requests, and in cases where there is little to no css in the file I find this inefficient.

我知道我可以使用脚本动态加载 css 文件,但这也意味着会有 2 个 http 请求,并且在文件中几乎没有 css 的情况下,我发现这效率低下。

So I thought to myself, what if you could put the css that you have in the css file, into the script, have the script parse the css and add it into the head, or even better just have the script add the css directly into the <head>of the document.

所以我想,如果你能把你在 css 文件中的 css 放到脚本中,让脚本解析 css 并将其添加到头部,或者甚至更好地让脚本直接将 css 添加到在<head>该文件中。

But I have found nothing online that suggests that this is possible, so is it possible to add css to the head with js?

但是我在网上没有发现任何表明这是可能的,那么是否可以使用js将css添加到头部?

Edit + SOLUTION:

编辑+解决方案:

I edited roryf's answer to work cross browser (except IE5)

我编辑了 roryf 的答案以跨浏览器工作(IE5 除外)

Javascript:

Javascript:

 function addcss(css){
    var head = document.getElementsByTagName('head')[0];
    var s = document.createElement('style');
    s.setAttribute('type', 'text/css');
    if (s.styleSheet) {   // IE
        s.styleSheet.cssText = css;
    } else {                // the world
        s.appendChild(document.createTextNode(css));
    }
    head.appendChild(s);
 }

采纳答案by moefinley

As you are trying to add a string of CSS to <head>with JavaScript? injecting a string of CSS into a page it is easier to do this with the <link>element than the <style>element.

当您尝试<head>使用 JavaScript添加一串 CSS时?将一串 CSS 注入页面,使用<link>元素比使用<style>元素更容易做到这一点。

The following adds p { color: green; }rule to the page.

以下p { color: green; }为页面添加规则。

<link rel="stylesheet" type="text/css" href="data:text/css;charset=UTF-8,p%20%7B%20color%3A%20green%3B%20%7D" />

You can create this in JavaScript simply by URL encoding your string of CSS and adding it the HREFattribute. Much simpler than all the quirks of <style>elements or directly accessing stylesheets.

您可以在 JavaScript 中创建它,只需通过 URL 编码您的 CSS 字符串并将其添加到HREF属性。比<style>元素的所有怪癖或直接访问样式表要简单得多。

var linkElement = this.document.createElement('link');
linkElement.setAttribute('rel', 'stylesheet');
linkElement.setAttribute('type', 'text/css');
linkElement.setAttribute('href', 'data:text/css;charset=UTF-8,' + encodeURIComponent(myStringOfstyles));

This will work in IE 5.5 upwards

这将适用于 IE 5.5 以上

The solution you have marked will work but this solution requires fewer dom operations and only a single element.

您标记的解决方案将起作用,但该解决方案需要较少的 dom 操作并且只需要一个元素。

回答by thomaux

Edit: As Atspulgs comment suggest, you can achieve the same without jQuery using the querySelector:

编辑:正如 Atspulgs 评论所建议的,您可以使用querySelector在没有 jQuery 的情况下实现相同的效果:

document.querySelector('head').innerHTML += '<link rel="stylesheet" href="styles.css" type="text/css"/>';

Older answer below.

下面的旧答案。



You could use the jQuerylibrary to select your head element and append HTML to it, in a manner like:

您可以使用jQuery库来选择您的 head 元素并将 HTML 附加到它,方式如下:

$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');

You can find a complete tutorial for this problem here

您可以在此处找到针对此问题的完整教程

回答by Jeriko

If you don't want to rely on a javascript library, you can use document.write()to spit out the required css, wrapped in styletags, straight into the document head:

如果你不想依赖一个 javascript 库,你可以使用document.write()将需要的 css 用style标签包裹起来,直接放到文档中head

<head>
  <script type="text/javascript">
    document.write("<style>body { background-color:#000 }</style>");
  </script>
  # other stuff..
</head>

This way you avoid firing an extra HTTP request.

这样您就可以避免触发额外的 HTTP 请求。

There are other solutions that have been suggested / added / removed, but I don't see any point in overcomplicating something that already works fine cross-browser. Good luck!

已经建议/添加/删除了其他解决方案,但我认为过度复杂化已经在跨浏览器上运行良好的东西没有任何意义。祝你好运!

http://jsbin.com/oqede3/edit

http://jsbin.com/oqede3/edit

回答by roryf

A simple non-jQuery solution, albeit with a bit of a hack for IE:

一个简单的非 jQuery 解决方案,尽管对 IE 有一点小技巧:

var css = ".lightbox { width: 400px; height: 400px; border: 1px solid #333}";

var htmlDiv = document.createElement('div');
htmlDiv.innerHTML = '<p>foo</p><style>' + css + '</style>';
document.getElementsByTagName('head')[0].appendChild(htmlDiv.childNodes[1]);

It seems IE does not allow setting innerText, innerHTMLor using appendChildon styleelements. Here is a bug reportwhich demonstrates this, although I think it identifies the problem incorrectly. The workaround above is from the comments on the bug report and has been tested in IE6 and IE9.

看来IE不允许设置innerTextinnerHTML或使用appendChildstyle的元素。这是一个错误报告,它演示了这一点,尽管我认为它错误地识别了问题。上面的解决方法来自对错误报告的评论,并且已经在 IE6 和 IE9 中进行了测试。

Whether you use this, document.write or a more complex solution will really depend on your situation.

无论您使用它、document.write 还是更复杂的解决方案,都将真正取决于您的情况。

回答by Tim Down

Here's a function that will dynamically create a CSS rule in all major browsers. createCssRuletakes a selector (e.g. "p.purpleText"), a rule (e.g. "color: purple;") and optionally a Document(the current document is used by default):

这是一个可以在所有主要浏览器中动态创建 CSS 规则的函数。 createCssRule接受一个选择器(例如“p.purpleText”)、一个规则(例如“color: Purple;”)和可选的a Document(默认使用当前文档):

var addRule;

if (typeof document.styleSheets != "undefined" && document.styleSheets) {
    addRule = function(selector, rule) {
        var styleSheets = document.styleSheets, styleSheet;
        if (styleSheets && styleSheets.length) {
            styleSheet = styleSheets[styleSheets.length - 1];
            if (styleSheet.addRule) {
                styleSheet.addRule(selector, rule)
            } else if (typeof styleSheet.cssText == "string") {
                styleSheet.cssText = selector + " {" + rule + "}";
            } else if (styleSheet.insertRule && styleSheet.cssRules) {
                styleSheet.insertRule(selector + " {" + rule + "}", styleSheet.cssRules.length);
            }
        }
    }
} else {
    addRule = function(selector, rule, el, doc) {
        el.appendChild(doc.createTextNode(selector + " {" + rule + "}"));
    };
}

function createCssRule(selector, rule, doc) {
    doc = doc || document;
    var head = doc.getElementsByTagName("head")[0];
    if (head && addRule) {
        var styleEl = doc.createElement("style");
        styleEl.type = "text/css";
        styleEl.media = "screen";
        head.appendChild(styleEl);
        addRule(selector, rule, styleEl, doc);
        styleEl = null;
    }
};

createCssRule("body", "background-color: purple;");

回答by Ally

Here's a simple way.

这里有一个简单的方法。

/**
 * Add css to the document
 * @param {string} css
 */
function addCssToDocument(css){
  var style = document.createElement('style')
  style.innerText = css
  document.head.appendChild(style)
}