我想为预加载器gif添加延迟。我按照这个http://www.netavatar.co.in/2011/05/31/how-to-show-a-loading-gif-image-while-a-page-loads-using-javascript-and-css/教程开始工作,但是我想在页面加载时显示加载gif至少3秒。
谢谢你的帮助
<script type="text/javascript">// <![CDATA[
function preloader(){
document.getElementById("loading").style.display = "none";
document.getElementById("content").style.display = "block";
}//preloader
window.onload = preloader;
// ]]></script>
答案 0 :(得分:2)
如何使用setTimeout
?
<script type="text/javascript">// <![CDATA[
function preloader(){
setTimeout(function() {
document.getElementById("loading").style.display = "none";
document.getElementById("content").style.display = "block";
}, 3000);
}//preloader
window.onload = preloader;
// ]]></script>
上面将显示加载时间和接下来3秒的加载。如果您希望实现“显示加载至少3秒,但加载时间超过3秒时立即隐藏”,则可以使用:
<script type="text/javascript">// <![CDATA[
var minimumShowLoadingTimeReached = false;
setTimeout(function() {minimumShowLoadingTimeReached = true;}, 3000);
function preloader() {
if (minimumShowLoadingTimeReached) {
showContent();
} else {
setTimeout(function() {
preloader();
}, 500);
}
}
function showContent(){
document.getElementById("loading").style.display = "none";
document.getElementById("content").style.display = "block";
}
window.onload = preloader;
// ]]></script>
它如何运作?
答案 1 :(得分:1)
<script type="text/javascript">// <![CDATA[
function preloader(secs){
if (secs >= 3) {
document.getElementById("loading").style.display = "none";
document.getElementById("content").style.display = "block";
} else {
setTimeout(function(){preloader(secs+1);},1000);
}
}
window.onload = preloader(0);
// ]]></script>