[英]jQuery Append CSS File and Wait until styles are applied without setInterval?
我加载CSS:
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
它工作,但我有一个功能,需要在应用CSS后运行,我不想使用setInterval
。
我怎样才能做到这一点 ?
一个解决方案,如果您可以访问正在加载的css文件,
是使用transitionend
事件,并从您的CSS激活duration
设置为0.1的转换。
像这样,你确定CSS已经计算好了。
style2.css
body{opacity:1;}
的index.html
<style>
body{transition : opacity 0.1s linear; opacity:.9};
</style>
<body>
...
<script>
document.body.addEventListener('transitionend', function(){
alert('done');
}, false);
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
编辑:
对于需要js功能的(没有外部文件): https : //jsfiddle.net/t0akchuw/
您可以使用load事件
$('<link />', { rel: 'stylesheet', ref: 'https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.css', type: 'text/css', onload: function() { snippet.log('loaded') } }).appendTo('head')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
另一种语法
$('head').append('<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.css" type="text/css" onload="dosomething()" />');
function dosomething(){
alert('d')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.