我一直在开发一个函数,它的功能有点像我希望它做的那样,如上所示,但我遇到了一个问题,它一次交换两个 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 Budget2,它应该循环运行,到目前为止列出的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>
这更加干净且易于调试。然后,您不应该在这里使用 ids,而是使用特定的类来显示/隐藏它们:
<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
});
如果您的代码中有其他不想切换的 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 代码。
关于javascript - 一次交换两个 Div,然后将它们交换为不同的两个 Div,并保持循环一定的秒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20288036/