gpt4 book ai didi

javascript - 使 2 个 div 出现在不同的延迟上

转载 作者:行者123 更新时间:2023-12-02 17:17:54 25 4
gpt4 key购买 nike

我试图让一个 div 在延迟后出现,而另一个 div 在另一次延迟后出现。两个代码单独工作,但不能一起工作。我更改了所有变量,为什么这不起作用?我知道您也许可以用不同的方式解决这个问题,但我希望它采用这种格式。谢谢

<script>
//appear after 1 second
window.onload = function(){

var theDelay = 1;
var timer = setTimeout("showText()",theDelay*1000)
}
function showText(){
document.getElementById("delayedText").style.visibility = "visible";
}
</script>
<div id="delayedText" style="visibility:hidden">
1st Text
</div>


<script>
//appear after 2 seconds
window.onload = function(){

var theDelay2 = 2;
var timer2 = setTimeout("showText2()",theDelay2*1000)
}
function showText2(){
document.getElementById("delayedText2").style.visibility = "visible";
}
</script>
<div id="delayedText2" style="visibility:hidden">
Appear 2nd
</div>

最佳答案

您将通过再次定义第一个 window.onload 来取消它。合而为一。

<div id="delayedText" style="visibility:hidden">1st Text</div>
<div id="delayedText2" style="visibility:hidden">Appear 2nd</div>

<script>
window.onload = function(){
var theDelay = 1;
var timer = setTimeout("showText()",theDelay*1000)
var theDelay2 = 2;
var timer2 = setTimeout("showText2()",theDelay2*1000)
}

function showText(){
document.getElementById("delayedText").style.visibility = "visible";
}

function showText2(){
document.getElementById("delayedText2").style.visibility = "visible";
}
</script>

http://jsfiddle.net/5DgQS/

或者,如果您需要单独添加 window.onload 事件,则无需每次都进行覆盖。我会使用一个函数来控制它。例如

// create the function to add a window.onload event

if (typeof addLoadEvent!='function' ){
function addLoadEvent(func){
var oldonload = window.onload;
if (typeof window.onload != 'function'){
window.onload = func;
}else{
window.onload = function(){
oldonload();
func();
}
}
}
}


// reuse it as many times as you want

addLoadEvent(function(){

var theDelay = 1;
var timer = setTimeout("showText()",theDelay*1000)

});

addLoadEvent(function(){

var theDelay2 = 2;
var timer2 = setTimeout("showText2()",theDelay2*1000)

});

http://jsfiddle.net/5DgQS/1/

关于javascript - 使 2 个 div 出现在不同的延迟上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24249304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com