【问题标题】:jQuery .load(function) and .addClass in Order to Remove Preloader is Not Working为了删除预加载器的 jQuery .load(function) 和 .addClass 不起作用
【发布时间】:2017-04-09 17:04:44
【问题描述】:

我目前正在使用 jQuery "addClass" 和 "removeClass" 来删除预加载器。我希望在加载所有 Web 内容时删除预加载器页面。设置超时功能似乎可以正常工作,但是当整个站点完成加载时,我似乎无法像实时加载那样做同样的事情。非常感谢一些帮助。

//..HTML..//

<div class="loader-wrapper">
</div>

//..CSS..//

.loader-wrapper {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}

.loaded .loader-wrapper {
-webkit-transform: translateY(120%);
-ms-transform: translateY(120%);
transform: translateY(120%);
-webkit-transition: all 1s 0.5s ease-out;
transition: all 1s 0.5s ease-out;
}

//..jQuery..//

<script>
  $("body").removeClass('loaded');
</script>

<script>
$( window ).load(function() {
 $("body").addClass('loaded');
});
</script>


//..For reference this works perfectly..//

<script>
$(document).ready(function() {

setTimeout(function() {
$("body").addClass('loaded');
}, 1800)

});
</script>

【问题讨论】:

  • 将 JS 代码放在两个单独的脚本标签中的任何具体原因?
  • 对我来说看起来有点干净。
  • 很公平,我个人不会推荐它as there are reasons against it,但无论如何。你的 html 是什么样的,你在做任何 ajax 调用吗?
  • 我已经包含了我的 html,它非常简单,是的,我已经有了 jQuery Ajax。对于更复杂的网站,我会记住脚本标签。

标签: javascript jquery css preloader jquery-load


【解决方案1】:

您可以使用一个库来验证所有图像何时加载。例如imagesLoaded

所以你的代码可能看起来像这样:

// DOM is ready
$(function() {
    // We have to make sure that all of the images are loaded in the container
    $('body').imagesLoaded( function() {
        // Images are loaded
        $('.loader').hide();
        $('img').show();
    });
});
img {
    display: none
}
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script src="https://npmcdn.com/imagesloaded@4.1/imagesloaded.pkgd.js"></script>

<span class='loader'>Loading ...</span>
<img width="200" src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a" />

【讨论】:

  • 我之前也尝试过这样做,但也没有用。
  • 也许你错过了什么。请在这里查看我的答案,因为作者确认它有效:stackoverflow.com/a/39938004/4312466
  • 我会看看它,但仅供参考,我编辑了我的帖子,你可以看到超时功能正常工作。
  • 感谢您的回答,但它似乎仍然不起作用,我很不确定为什么。您的代码理论上应该可以工作。如果您有兴趣进一步研究,我提供了一个指向我的网站的链接。
  • 我已经更新了我的答案并添加了一个小提琴。确保您的代码符合我的想法。
【解决方案2】:
You can use the $(document).ready(function(){ // code  }); 

,如果您正在等待网页完全加载。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 2013-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多