![](/img/trans.png)
[英]Appending a stylesheet to the head of an html document using JavaScript
[英]Add stylesheet to Head using javascript in body
我正在使用阻止我们编辑头部部分的 CMS。 我需要在标签之后将 css 样式表添加到站点。 有没有办法用 JS 来做到这一点,我可以在页面底部添加一个脚本(我可以在标签之前添加脚本),然后将样式表注入到 head 部分?
更新:根据 规范,正文中不允许使用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').append('<link rel="stylesheet" type="text/css" href="{url}">')
正如胡安门德斯所说,您可以将样式表插入头部
$('head').append('<link rel="stylesheet" type="text/css" href="{url}">')
没有 jQuery 也一样(见上面的代码)
这将以一种智能的方式做你想做的事。 也使用纯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);
}
我修改了 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
您可以在现代浏览器中使用纯 javascript 并且仍然优雅。
const range = document.createRange()
const frag = range.createContextualFragment(`THE CONTENT IS THE SAME AS THE HTML.`)
document.querySelector("YOUR-NODE").append(frag)
添加任何 HTML 代码非常容易。
通过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>
导入 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
这是添加样式表的简单单行代码:
document.head.insertAdjacentHTML('beforeend', `<link typs="text/css" rel="stylesheet" href="<Source URL>">`);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.