同时换掉两个Div,换成另一个Div并保持循环一段固定的秒数
Swap two Divs out at once and swap them for a different two and keep looping for a set amount of seconds
我一直在开发一个函数,它做了我想让它做的事情,如上所示,但它同时交换两个div并用不同的两个替换时遇到了问题,任何人都不知道该怎么做,下面是我到目前为止得到的:
$(function () {
var counter = 0,
divs = $('#budgetSpent,#budgetTitle,#staticBudget,#staticTitle');
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
}, 5 * 1000); // do this every 10 seconds
});
简短描述:所以我几乎有两个计数器,每10秒显示一个div,其余的都被隐藏,现在它确实交换了,但旁边有标题的两个div ID,我不能让它们与相应的计数器一起交换,比如说:0000英镑的Budget1(显示10秒)然后交换到11111英镑的Budget 2,它应该在循环中运行,到目前为止,列出的4个div每个setInterval都在逐个交换,但我需要一次显示和隐藏2个div,而不是一个接一个
首先,您必须保持代码简单。特别是当我们在SO上要求一些东西时。我们不想知道你的div中有什么,但我们只需要它们的HTML标记:
<div id='budgetTitle'>budgetTitle div</div>
<div id='staticBudget'>staticBudget div</div>
<div id='staticTitle'>staticTitle div</div>
<div id='budgetSpent'>BudgetSpent div</div>
这要干净得多,调试起来也很快。然后,你不应该在这里使用id,而是使用一个特定的类来显示/隐藏它们:
<div id='budgetTitle'>budgetTitle div</div>
<div id='staticBudget' class="hide">staticBudget div</div>
<div id='staticTitle'>staticTitle div</div>
<div id='budgetSpent' class="hide">BudgetSpent div</div>
用于隐藏div的CSS代码:
div.hide {display: none;}
现在您将只看到#budgetTitle
和#staticTitle
div。好吧,现在让我们开始"交换"部分:
您所需要的只是为其他div提供.hide
类,并从其他div中删除该类。有一种jQuery
方法:jQuery.toggleClass()
现在你只需要这样做就可以交换div:
// This will give all divs that don't have the "hide" class the class "hide"
// and remove the class "hide" from all divs that have the "hide" class
$('div').toggleClass('hide');
最终代码:
function swapDivs () {
$('div').toggleClass('hide');
}
$(function () {
setInterval(
function () {
swapDivs(); // show next div
},
3 * 1000
); // do this every 3 seconds
});
演示jsFiddle
如果您的代码中有其他不想切换的div,那么应该在这四个div中添加一个toggle
类:
<div id='budgetTitle' class="toggle">budgetTitle div</div>
<div id='staticBudget' class="toggle hide">staticBudget div</div>
<div id='staticTitle' class="toggle">staticTitle div</div>
<div id='budgetSpent' class="toggle hide">BudgetSpent div</div>
然后只需在js
:中进行一些更改
function swapDivs () {
$('div.toggle').toggleClass('hide');
}
如果您无法使其工作,请尝试从头开始(没有javascript、css和html),然后尝试在div中添加自己的html代码。
- 循环对象时更新页面上的DIV元素
- 同时换掉两个Div,换成另一个Div并保持循环一段固定的秒数
- For循环只打印一个DIV标记.不是8个DIV标签
- 使用 Ajax 循环附加 Div 类
- 循环遍历父 Div 并更改 Div 子类名称
- 如何在 while 循环中清除 DIV 并添加新内容
- 循环访问一系列 DIV 并淡入/淡出
- 从我的 Div 背景图像属性中循环 3 个图像
- 循环遍历DIV id数组,并每隔x秒刷新这些DIVS
- DIV与循环滚动
- 渐明,淡出DIV上循环工作良好-但不显示第一个DIV
- 在隐藏特定DIV和更新url之前,为循环预加载图像
- 反向拉伸从循环复制输出到DIV
- For循环没有创建Div
- 每10秒循环一次DIV +选择DIV
- 使用VBA循环遍历DIV元素
- 如何动态改变Div位置,它必须是for循环中的绝对位置
- while 循环 - 使用 JavaScript 在所有 DIV 标签之后添加元素
- 经过淡入/淡出循环的Div突然闪烁
- Javascript Div循环中的日期没有正确更新