我只是想要旋转地更改每个div框的背景颜色,当一个div框改为背景白色时,其余的框保持原始颜色,我的意思是不是白色,请参阅代码{{3 }}。知道怎么做到这一点?现在,下面的代码将所有框一次更改为白色,这不是预期的
<div class="container">
<div class="one">One</div>
<div class="two">Two</div>
<div class="three">Three</div>
<div class="four">Four</div>
</div>
setInterval(function(){
$("div.container div").each(function(event){
$(this).css("background-color", "white");
$("div.container div").not(this).css("background-color", "none");
});
}, 1000);
答案 0 :(得分:2)
您可以使用modulo operator进行此轮换:
var i = 0,
$tabs = $("div.container div");
setInterval(function () {
$tabs.removeClass('selectedtab').eq(i++ % $tabs.length).addClass('selectedtab');
}, 1000);
.container {
width: 121px;
padding:0;
margin:0;
padding: 5px;
margin-top:130px;
margin-left:130px;
border:2px solid blue;
display:inline-block;
height: 89px;
vertical-align: top;
}
.one {
border: 2px solid green;
width: 34px;
padding:10px;
background-color: yellow;
}
.two {
border: 2px solid green;
width: 34px;
padding:10px;
position: relative;
top: 1px;
background-color: orange;
}
.three {
border: 2px solid green;
margin-left: 59px;
position: relative;
top: -43px;
width: 30%;
padding:10px;
background-color: brown;
}
.four {
border: 2px solid green;
margin-left: 59px;
position: relative;
top: -132px;
width: 30%;
padding:10px;
background-color: darkred;
}
.selectedtab {
background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="one">One</div>
<div class="two">Two</div>
<div class="three">Three</div>
<div class="four">Four</div>
</div>
答案 1 :(得分:0)
见fiddle 您可以在间隔中检查要更改的div的索引,然后从所有其他类中删除背景
var index = 0;
setInterval(function() {
$("div.container div").each(function(i, event) {
if (i == index)
$(this).addClass("white");
else
$(this).removeClass('white');
});
index++;
}, 1000);
.container {
width: 121px;
padding: 0;
margin: 0;
padding: 5px;
margin-top: 130px;
margin-left: 130px;
border: 2px solid blue;
display: inline-block;
height: 89px;
vertical-align: top;
}
.one {
border: 2px solid green;
width: 34px;
padding: 10px;
background-color: yellow;
}
.two {
border: 2px solid green;
width: 34px;
padding: 10px;
position: relative;
top: 1px;
background-color: orange;
}
.three {
border: 2px solid green;
margin-left: 59px;
position: relative;
top: -43px;
width: 30%;
padding: 10px;
background-color: brown;
}
.four {
border: 2px solid green;
margin-left: 59px;
position: relative;
top: -132px;
width: 30%;
padding: 10px;
background-color: darkred;
}
.selectedtab {
background-color: white;
}
.white {
background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="one">One</div>
<div class="two">Two</div>
<div class="three">Three</div>
<div class="four">Four</div>
</div>
<小时/> 修改强>
如果您希望无限次发生这种情况,请使用模运算符,请参阅Fiddle