使用jQuery隐藏元素直到页面加载完成

9
我刚编写了一段简单的代码,用于在页面加载完成前隐藏所有元素并显示一个加载指示器。(它有效)。
所以我的问题是想知道我是否做得对,您有什么建议。 HTML
<body>
    <div class="loading">
        <img src="indicator.gif"/>
    </div>

    <div class="content">
        <!-- page content goes here --> 
    </div>
</body>

jquery

$(document).ready(function(){
        $(".content").hide();
     });

    $(window).load(function(){
        $(".loading").fadeOut("slow");
        $(".content").fadeIn("slow");
     });
2个回答

14

你可能想要从一开始就隐藏内容div,以避免根据页面加载的内容可能导致页面闪烁。

<body>
  <div class="loading">
    <img src="indicator.gif"/>
  </div>

  <div class="content" style="display: none;">
    <!-- page content goes here --> 
  </div>
</body>


$(window).load(function(){
  $(".loading").fadeOut("slow");
  $(".content").fadeIn("slow");
});

6
稍微改进一下这个Javascript代码是使用回调函数来控制淡出,这样淡入就会在淡出完成后开始。这样可以让过渡变得更加平滑。
<body>
  <div class="loading">
    <img src="indicator.gif"/>
  </div>

  <div class="content" style="display: none;">
    <!-- page content goes here --> 
  </div>
</body>


$(window).load(function(){
  $(".loading").fadeOut("slow", function(){
    $(".content").fadeIn("slow");
  });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接