首页 > 解决方案 > 在没有循环的 X 秒后显示/隐藏 Div 系列

问题描述

在页面加载时,我试图显示 div1 10 秒然后隐藏它,显示div23 秒然后隐藏它,然后显示最后一个 div3 而不隐藏它。

所以我在我的CSS...

#show1, #show2, #show3 {display: none; }

在 html...

<div id="showhide">
<div id="show1">
<h2>Step 1: Checking if your area is eligible...</h2>
</div>
<div id="show2">
<h2>Success!</h2>
</div>
<div id="show3">
<h2>Just need to gather a little more information...</h2>
</div>
</div>

还有一个正常的显示/隐藏脚本,但我不知道如何 1) 使其不循环和 2) 为 div1 和 div2 的显示/隐藏设置不同的间隔。

$(function () {

var counter = 0,
divs = $('#show1, #show2, #show3');

function showDiv () {
divs.hide() // hide all divs
.filter(function (index) { return index == counter % 3; }) // figure out correct div to show
.show('fast'); // and show it

counter++;
}; // function to loop through divs and show correct div

showDiv(); // show first div    

setInterval(function () {
showDiv(); // show next div
}, 1 * 1000); // do this every 10 seconds    

});

任何帮助,将不胜感激!

标签: javascript

解决方案


添加data-nextid="show2" data-showtimeout="10" class="hide-div" style="display:none;"<div>标签。

data-nextid将显示下一个 div 的 id。

data-showtimeout将具有当前 div 的显示时间值。

hide-div类用于将所有此类 div 设置为在函数调用时隐藏。

style="display:none;"到每个 div 最初将隐藏所有 div。

移除 CSS#show1, #show2, #show3 {display: none; }

添加了对 display first div displayDivWithTimer.apply($('#show1'));inside的初始调用$(document).ready()

function displayDivWithTimer() { 
  $(this).css('display', 'block');
  var timeout = $(this).attr('data-showtimeout');
  var nextid = $(this).attr('data-nextid');
  //console.log("timeout:" + timeout + ", nextid:" + nextid);
  if (timeout && nextid) {
    setTimeout(() => {
      $('.hide-div').css('display', 'none');
      displayDivWithTimer.apply($('#' + nextid));
    }, parseInt(timeout) * 1000);
  }  
}

$(document).ready(function() {
    displayDivWithTimer.apply($('#show1'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<div id="showhide">
  <div data-nextid="show2" data-showtimeout="10" id="show1" class="hide-div" style="display:none;">
    <h2>Step 1: Checking if your area is eligible...</h2>
  </div>
  <div data-nextid="show3" data-showtimeout="3" id="show2" class="hide-div" style="display:none;">
    <h2>Success!</h2>
  </div>
  <div id="show3" class="hide-div" style="display:none;">
    <h2>Just need to gather a little more information...</h2>
  </div>  
</div>


推荐阅读