使用javascript在正文中添加样式表为Head [英] Add stylesheet to Head using javascript in body

查看:205
本文介绍了使用javascript在正文中添加样式表为Head的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用CMS,无法编辑头部。我需要添加CSS样式表到网站,紧接在标签之后。有没有办法做到这一点与JS,在那里我可以添加一个脚本到页面的底部(我可以访问添加脚本的标签之前),然后将注入样式表到头部?

解决方案

更新:根据 specs 链接元素不允许在body中,但大多数浏览器现在仍然会渲染它很好。因此,在评论中回答问题 - 真的必须将链接添加到页面的,而不是< c $ c> body 。

  function addCss(fileName){

var head = document.head
,link = document.createElement('link')

link.type ='text / css'
link.rel ='stylesheet'
link.href = fileName

head.appendChild(link)
}

addCss('{my-url}')


$ b

  function addCss(fileName){
var link ='< link rel =stylesheettype =text / csshref ='+ fileName +'>'
$('head')。append(link)
}

addCss('{my-url}')






原始回答



  $('body') ').append('< link rel =stylesheettype =text / csshref ={url}>')
  $(
$ b) 'head')。append('< link rel =stylesheettype =text / csshref ={url}>')

而且没有jQuery(见上面的代码)


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?

解决方案

Update: According to specs link element is not allowed in the body however most browsers as of right now will still render it just fine. So to answer question in comments - one really have to add link to the head of the page and not the body.

function addCss(fileName) {

  var head = document.head
    , 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

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').append('<link rel="stylesheet" type="text/css" href="{url}">')

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

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

And the same without jQuery (see code above)

这篇关于使用javascript在正文中添加样式表为Head的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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