在正文中使用 javascript 将样式表添加到 Head

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

Add stylesheet to Head using javascript in body

javascriptcss

提问by Rahil Pirani

I'm working with a CMS that prevents us from editing the head section. I need to add css stylesheet to the site, right after the tag. Is there a way to do this with JS, where I can add a script to the bottom of the page (I have access to add script right before the tag) that would then inject the stylesheet into the head section?

我正在使用阻止我们编辑头部部分的 CMS。我需要将 css 样式表添加到站点,紧跟在标记之后。有没有办法用 JS 做到这一点,我可以在页面底部添加一个脚本(我可以在标签之前添加脚本),然后将样式表注入头部?

回答by vittore

Update: According to specs, the linkelement is not allowed in the body. However, most browsers will still render it just fine. So, to answer the questions in the comments - one really has to add linkto the headof the page and not the body.

更新:根据规范,该link元素不允许出现在正文中。但是,大多数浏览器仍然可以很好地呈现它。因此,要回答评论中的问题 - 确实必须添加linkhead页面的 ,而不是body.

function addCss(fileName) {

  var head = document.head;
  var link = document.createElement("link");

  link.type = "text/css";
  link.rel = "stylesheet";
  link.href = fileName;

  head.appendChild(link);
}

addCss('{my-url}');

Or a little bit easier with jquery

或者使用 jquery 更容易一点

function addCss(fileName) {
   var link = $("<link />",{
     rel: "stylesheet",
     type: "text/css",
     href: fileName
   })
   $('head').append(link);
}

addCss("{my-url}");


Original answer:

原答案

You don't need necessarily add it to the head, just add it to the end of body tag.

您不一定需要将其添加到头部,只需将其添加到 body 标签的末尾即可。

$('body').append('<link rel="stylesheet" type="text/css" href="{url}">')

as Juan Mendes mentioned, you can insert stylesheet to the head instead

正如 Juan Mendes 提到的,您可以将样式表插入头部

$('head').append('<link rel="stylesheet" type="text/css" href="{url}">')

And the same without jQuery (see code above)

没有 jQuery 也是一样(见上面的代码)

回答by Eddie

This will do what you want in an intelligent way. Also using pure JS.

这将以一种智能的方式做你想做的事。也使用纯JS。

function loadStyle(href, callback){
    // avoid duplicates
    for(var i = 0; i < document.styleSheets.length; i++){
        if(document.styleSheets[i].href == href){
            return;
        }
    }
    var head  = document.getElementsByTagName('head')[0];
    var link  = document.createElement('link');
    link.rel  = 'stylesheet';
    link.type = 'text/css';
    link.href = href;
    if (callback) { link.onload = function() { callback() } }
    head.appendChild(link);
}

回答by cronoklee

I've modified Eddie's function to removeor togglethe stylesheet on or off. It will also return the current state of the stylesheet. This is useful for example, if you want to have a toggle button on your website for vision-impaired users and need to save their preference in a cookie.

我修改Eddie的功能来删除切换样式表或关闭。它还将返回样式表的当前状态。这很有用,例如,如果您想在您的网站上为视力受损用户设置一个切换按钮,并且需要将他们的偏好保存在 cookie 中。

function toggleStylesheet( href, onoff ){
    var existingNode=0 //get existing stylesheet node if it already exists:
    for(var i = 0; i < document.styleSheets.length; i++){
        if( document.styleSheets[i].href && document.styleSheets[i].href.indexOf(href)>-1 ) existingNode = document.styleSheets[i].ownerNode
    }
    if(onoff == undefined) onoff = !existingNode //toggle on or off if undefined
    if(onoff){ //TURN ON:
        if(existingNode) return onoff //already exists so cancel now
        var link  = document.createElement('link');
        link.rel  = 'stylesheet';
        link.type = 'text/css';
        link.href = href;
        document.getElementsByTagName('head')[0].appendChild(link);
    }else{ //TURN OFF:
        if(existingNode) existingNode.parentNode.removeChild(existingNode)
    }
    return onoff
}

Sample usage:

示例用法:

toggleStylesheet('myStyle.css') //toggle myStyle.css on or off

toggleStylesheet('myStyle.css',1) //add myStyle.css

toggleStylesheet('myStyle.css',0) //remove myStyle.css