如何使用jquery加载CSS

问题描述 投票:50回答:4

我在服务器上加载了一个css文件,所以我有一个URL跟我一起。如何使用JQuery在我的perl代码中加载它?

所以目前我在我的梅森页面中硬编码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; } "]});
});

我想避免硬编码这个CSS?

jquery html css stylesheet
4个回答
75
投票

我不明白为什么你不能只在<link/>部分插入<head/>元素,但这里是一个jQuery片段:

$('head').append( $('<link rel="stylesheet" type="text/css" />').attr('href', 'your stylesheet url') );

40
投票

再次,根据Dynamically loading css stylesheet doesn't work on IE

你需要设置最后的href attr,并且只有在链接元素附加到头部之后:

$('<link>')
  .appendTo('head')
  .attr({
      type: 'text/css', 
      rel: 'stylesheet',
      href: '/css/your_css_file.css'
  });

0
投票
$(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)});

0
投票

我喜欢对语言和文件类型保持一致(例如:不要将CSS与html混合)。所以我会创建一个style.css文件并使用jQuery将其加载到标记中。

的index.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;
}
© www.soinside.com 2019 - 2024. All rights reserved.