如何在window.onload上调用选定的类

时间:2015-07-07 11:46:47

标签: javascript jquery

我做了一个简单的javascript,它在window.onload完成时在体内消失。

我想创建一个具有特定类的覆盖,而不是反过来。我希望叠加层简单地淡出,在动画之后,对象将被销毁或设置为display:none



<style>
	body {
		opacity: 0;
		transition: opacity 500ms ease-in-out;
		}
</style>
<script>window.onload = function() {setTimeout(function(){document.body.style.opacity="100";},500);};</script>
&#13;
&#13;
&#13;

如何以最佳方式实现这一目标?

2 个答案:

答案 0 :(得分:0)

你问了一个jQuery标签,所以我用jQuery代码来回答你。

&#13;
&#13;
$(function() {
    var $overlay = $('#overlay');
  
    $overlay.css('opacity', 0);
  
    setTimeout(function() {
       $overlay.remove();
    }, 500);
});
&#13;
#overlay {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: white;
    transition: opacity 500ms;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text   
</div>

<div id="overlay"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以通过在加载时向<body>添加一个类并在CSS中定义任何样式和转换来实现此目的。

虽然这种技术可以确保整个文档的继承,但是启用任意数量的解决方案,最直接的方法是在:after上使用<body>伪元素:

window.onload = function () {
  
  // add a 'ready' class once the window has loaded
  document.body.classList.add("ready");
};
body {
  background: red;
  color: white;
  text-align: center;
}

/* this creates your overlay without unnecessary HTML markup */
body::after {
  content: "";
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: white;
}

/* transition the overlay out when body has a 'ready' class */
body.ready::after {
  opacity: 0;
  visibility: hidden;
  
  /* transitioning visibility to "hidden" allows a seamless opacity transition */
  transition-property: opacity, visibility;
  
  /* Set your animation duration here */
  transition-duration: 0.4s;
}
<h1>Awesome content</h1>

旁注:为了允许没有启用JavaScript的用户(否则会看到空白屏幕),您可能还会考虑在<html>上允许“no-js”类(替换为你<head>中的'js'。那么你的css伪声明将是:html.js body::after{...}。更多信息:What is the purpose of the HTML "no-js" class?