如何使用 jquery 加载 CSS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3913359/
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
How to load CSS using jquery
提问by TopCoder
I have loaded a css file on server so I am having a URL with me. How can i load it in my perl code using JQuery ?
我已经在服务器上加载了一个 css 文件,所以我有一个 URL。如何使用 JQuery 在我的 perl 代码中加载它?
So currently I am hardcoding the css in my mason page which is missing from the page something like this
所以目前我正在我的 mason 页面中对 css 进行硬编码,该页面中缺少这样的页面
JQ.onReady('show', function(){
JQ.addStyles({styles: ["\n\n.ap_classic { border-top:1px solid #ccc;border-left:1px solid #ccc;border-bottom:1px solid #2F2F1D; border-right:1px solid #2F2F1D;background-color:#EFEDD4;padding:3px; } .ap_classic .ap_titlebar { color:#86875D;font-size:12px;padding:0 0 3px 0;line-height:1em; } .ap_classic .ap_close { float:right; } .ap_classic .ap_content { clear:both;background-color:white;border:1px solid #ACA976;padding:8px;font-size:11px; } "]});
});
I want to avoid hardcoding this css ?
我想避免硬编码这个 css 吗?
回答by pawel
I don't get why you can not just insert the <link/>
element in the <head/>
section, but here's a jQuery snippet:
我不明白为什么不能只<link/>
在该<head/>
部分中插入元素,但这是一个 jQuery 片段:
$('head').append( $('<link rel="stylesheet" type="text/css" />').attr('href', 'your stylesheet url') );
回答by ekerner
Again, as per Dynamically loading css stylesheet doesn't work on IE.
同样,根据动态加载 css 样式表在 IE 上不起作用。
You need to set the href attr last and only after the link elem is appended to the head:
您需要最后设置 href attr 并且仅在链接 elem 附加到头部之后:
$('<link>')
.appendTo('head')
.attr({
type: 'text/css',
rel: 'stylesheet',
href: '/css/your_css_file.css'
});
回答by EMW
$(document).ready(function(){
console.log("ready!");
var e=$("<link>",{
rel:"stylesheet",
type:"text/css",
href:"/your/css/file.css"})[0];
e.onload=function(){
console.log("CSS IN IFRAME LOADED")},
document.getElementsByTagName("head")[0].
appendChild(e)});
回答by Tudor Morar
I like being consistent about language and file type (ex: don't mix css with html). So I would go for creating a style.css file and loading it into a tag with jQuery.
我喜欢在语言和文件类型方面保持一致(例如:不要将 css 与 html 混合)。所以我会去创建一个 style.css 文件并用 jQuery 将它加载到一个标签中。
index.html
索引.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div>
<style id="import"></style>
<h2 class="red">this is red</h2>
</div>
<script type="text/javascript">
$( document ).ready(function() {
$( "#import" ).load( "./style.css" );
});
</script>
</body>
</html>
style.css
样式文件
.red{
color: red;
}