how to enable/disable div using javascript in time

2019-09-01 13:38发布

问题:

I have three div's on my page. I want to show the div's one by one using timer in javascript. that means, when the first div is on, the other 2 should be off and henceforth...

Please reply with some codes in javascript...

回答1:

let's say you have these elements:

<div id="el1">element 1</div>
<div id="el2">element 2</div>
<div id="el3">element 3</div>

start by not displaying them:

<style>
#el1,#el2,#el3{display:none;}
</style>

then show them one by one:

<script>
(function(){
  var i=1;
  function show(){
    for(var j=1;j<4;++j)document.getElementById('el'+j).style.display='none';
    document.getElementById('el'+i).style.display='block';
    if(3==i++)return;
    setTimeout(show, 2000);
  }
  show();
})();
</script>

(the above is not tested)