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

时间:2014-06-16 17:44:19

标签: javascript html delay

我试图让一个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>

1 个答案:

答案 0 :(得分:2)

您正在取消第一个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事件,则可以在不重写每次的情况下执行此操作。我会用一个函数来控制它。 e.g。

// 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/