繁体   English   中英

jQuery附加CSS并运行一个函数?

[英]jQuery appending a CSS and running a function?

我试图将CSS文件附加到当前的HTML页面,如下所示:

    var css = jQuery("<link>");
    css.attr({
      rel:  "stylesheet",
      type: "text/css",
      href: "http://domain.com/chron/css/jquery.gritter.css"
    });
    $("head").append(css);

一旦下载了css文件,我想调用一个特定的函数。 我想我会把函数调用放在$('head').append(css); 但是我不确定这是否能保证在调用函数之前首先下载css文件。 有人可以告诉我该怎么做?

如何通过AJAX检索并将其放在STYLE元素中:

$.ajax( {
    url: 'http://domain.com/chron/css/jquery.gritter.css'
    dataType: 'text'
    success: function( data )
    {
        $( '<style>' )
            .attr( 'type', 'text/css' )
            .text( data )
            .appendTo( 'head' );

        yourFunction();
    }
} );

好。 标记应该具有名为complete的属性,在加载时设置为true。 如果你想要或者onload可以工作,你可以每50毫秒测试一次。

例如

var css = jQuery("<link>");
css.attr({
  rel:  "stylesheet",
  type: "text/css",
  href: "http://domain.com/chron/css/jquery.gritter.css"
})
.load(function() { /* callback */ });
$("head").append(css);

//As i have no idea whether the onload event
//works on link elements or not, try this instead:
setTimeout(function(){
    if(!css.complete)
    { setTimeout(arguments.callee, 50); }
    else
    { /* callback */ }
}, 50);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM