【问题标题】:jQuery Append CSS File and Wait until styles are applied without setInterval?jQuery 追加 CSS 文件并等到在没有 setInterval 的情况下应用样式?
【发布时间】:2017-09-09 14:09:14
【问题描述】:

我通过以下方式加载 CSS:

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

它可以工作,但我有一个需要在应用 CSS 后运行的函数,我不想为此使用 setInterval

我该怎么做?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

一个解决方案,如果您可以访问正在加载的 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/

【讨论】:

  • 嗨@Kaiido,我有一个问题,如果css文件在0.1s内不能应用,transitionend不会被触发。而且我无法确定加载 css 文件的时间?
  • 我认为转换是最后计算的,虽然不能确定,但​​我认为它不应该发生,不是吗?
  • 好一个!我想更正一个小错字('transtionend' 到 'transitionend'),但我不能,因为它的更改少于 6 个字符。
【解决方案2】:

您可以使用load event

$('<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')
}

【讨论】:

  • 谢谢,但在这种情况下,它会在发送请求时调用 onload(),但不是加载 css 完成
猜你喜欢
  • 2012-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-25
相关资源
最近更新 更多