How can call a selected class on window.onload

I have made a simple javascript which during window.onload fades in the body when finished.

I want to create an overlay with a specific class instead which shall do the reverse. I want the overlay to simply fade out and after the animation the object would be destroyed or set as 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>

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

$(function() {
    var $overlay = $('#overlay');
  
    $overlay.css('opacity', 0);
  
    setTimeout(function() {
       $overlay.remove();
    }, 500);
});
#overlay {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: white;
    transition: opacity 500ms;
}
<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>

You can achieve this by adding a class to <body> on load and defining any styles and transitions in CSS.

While this technique ensures inheritance throughout your document, enabling any number of solutions, the most straightforward is to utilise an :after pseudo element on your <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>
链接地址: http://www.djcxy.com/p/96880.html

上一篇: 图像闪烁和预防。 适当的编码标准

下一篇: 如何在window.onload上调用选定的类