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

时间:2012-08-06 18:21:49

标签: javascript css

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

4 个答案:

答案 0 :(得分:72)

更新:根据specs,正文中不允许使用link元素。但是,大多数浏览器仍然可以正常渲染它。因此,要回答评论中的问题 - 必须将link添加到页面的head而不是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}');

或者使用jquery

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

addCss("{my-url}");

原始答案

您无需将其添加到头部,只需将其添加到body标记的末尾。

$('body').append('<link rel="stylesheet" type="text/css" href="{url}">')
如Juan Juandes所述,你可以将样式表插入头部而不是

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

没有jQuery(见上面的代码)

答案 1 :(得分:16)

这将以智能方式完成您想要的任务。也使用纯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);
}

答案 2 :(得分:5)

我已将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
}

样本使用:

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

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

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

答案 3 :(得分:0)

您可以在现代浏览器中使用纯 JavaScript 并保持优雅。

const range = document.createRange()
const frag = range.createContextualFragment(`THE CONTENT IS THE SAME AS THE HTML.`)
document.querySelector("YOUR-NODE").append(frag) 

添加任何 HTML 代码非常容易。

文档

示例 1

通过javascript在头部添加样式。

<head></head><body><button class="hover-danger">Hello World</button></body>
<script>
  const range = document.createRange()
  const frag = range.createContextualFragment(`
<style>
  .hover-danger:hover{
    background-color: red;
    font-weight: 900
  }
</style>
`
)
  document.querySelector("head").append(frag)  
</script>

示例 2

导入 CSS、JS 并修改现有样式表。

<head></head>
<body><button class="btn btn-primary hover-danger">Hello world</button></body>

<script>
  const range = document.createRange()
  const frag = range.createContextualFragment(`
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"/>
`)
  document.querySelector("head").append(frag)

  window.onload = () => {
    // ? If you don't want to import the new source, you can consider adding the data to exists source.
    const nodeLink = document.querySelector(`link[href^="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"]`) // ^: match begin with my input
    if (nodeLink)  { // !== null
      const stylesheet = nodeLink.sheet
      const myCSS = `
background-color:red;
font-weight: 900;
`
      stylesheet.insertRule(`.hover-danger:hover{ ${myCSS} }`, stylesheet.cssRules.length)
    }
  }
</script>

<块引用>

? 必须有权限才能直接修改 CSS

如果出现错误:

<块引用>

无法从“CSSStyleSheet”读取“cssRules”属性:无法访问规则,

那么你可以参考:https://stackoverflow.com/a/49994161/9935654

相关问题