簡體   English   中英

如何在window.onload上調用選定的類

[英]How can call a selected class on window.onload

我做了一個簡單的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> 

如何以最好的方式做到這一點?

您用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> 

您可以通過在加載時將類添加到<body>並定義CSS中的任何樣式和過渡來實現。

盡管此技術可確保在整個文檔中進行繼承,從而啟用任何數量的解決方案,但最直接的方法是在<body>上使用:after偽元素:

 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{...} 更多信息: HTML“ no-js”類的目的是什么?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM