javascript - 在没有循环的 X 秒后显示/隐藏 Div 系列
问题描述
在页面加载时,我试图显示 div1 10 秒然后隐藏它,显示div2
3 秒然后隐藏它,然后显示最后一个 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
});
任何帮助,将不胜感激!
解决方案
添加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>
推荐阅读
- java - 在Android错误中通过长按从列表视图中删除项目
- excel - VBA如何将图像文件路径作为超链接提交到数据库
- angular - 使用 ngDoCheck 的成本是多少?
- python-3.x - 模块“matplotlib”没有属性“艺术家”,Matplotlib 3.0.0
- ios - 从 Swift 的 TimeInterval 中删除时间组件?
- python - 在用于图像分类的大型数据集上训练和测试精度没有希望
- python - Google Authenticator 的密钥是否应该保密?
- python - Django REST Framework:创建用户不需要密码,发送时密码不保存
- vb.net - 为测验的一组按钮添加分数
- themes - 为什么我的 powerlevel9k 提示中出现“cherry-or-revert”?