是否可以每隔x秒在div之间自动切换活动类? 不停?我的意思是无限循环。
尝试了setInterval和addClass到progfill,没有成功,任何解决方案? 感谢
<div class="progress">
<div class="progfill"></div>
</div>
<div class="progress">
<div class="progfill"></div>
</div>
<div class="progress">
<div class="progfill"></div>
</div>
我需要添加&#39;有效的&#39; class to progfill class,例如:
第二次迭代:
答案 0 :(得分:2)
这样的事情可能是:
var x = 1;
function updateClass() {
let a = $(".progfill.active");
a.removeClass("active");
a = a.parent().next(".progress");
if (a.length == 0)
a = $(".progress").first();
a.find(".progfill").addClass("active");
}
$(document).ready(function() {
setInterval(function() {
updateClass();
}, x * 1000);
});
.progfill {
width: 50px;
height: 50px;
background-color: red;
}
.active {
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="progress">
<div class="progfill active"></div>
</div>
<div class="progress">
<div class="progfill"></div>
</div>
<div class="progress">
<div class="progfill"></div>
</div>
x
表示更改之间的秒数,您可以对其进行调整。
答案 1 :(得分:1)
请看一下我的解决方案。它使用递归的setTimeout,其性能优于setInterval。
了解为什么递归setTimeout更好 - &gt; https://develoger.com/settimeout-vs-setinterval-cff85142555b
另外,只需进行一些更改,您就可以使用任何想要在每X秒重复X次的功能。
在此处查看完整的笔代码 - &gt; https://codepen.io/nikolamitic/pen/ypMNaN
// Be able to:
// 1. Define function that takes some arguments
// 2. Be ablle to call that function X number of time every X seconds
// 3. On each iteration that fun takes other param
const elmnt = document.querySelectorAll('.item');
const numberOfelmnt = document.querySelectorAll('.item').length;
const activeClass = 'active';
const repeat = (numberOfIterations, timeBetweenItereation, stuffToRepeat) => {
let iterationCounter = 0;
const repeater = () => {
setTimeout( () => {
stuffToRepeat(elmnt[iterationCounter], activeClass);
iterationCounter++;
if (numberOfIterations === iterationCounter) {
iterationCounter = 0;
};
if (iterationCounter >= numberOfIterations) {
return;
};
repeater();
}, 1000 * timeBetweenItereation);
};
repeater();
};
const addClassToElmnt = (elmnt, className) => {
let elmntWithClassToRemove = document.getElementsByClassName(className);
[...elmntWithClassToRemove].forEach((curentElmnt)=>{
curentElmnt.classList.remove(className);
});
elmnt.classList.add(className);
};
repeat(numberOfelmnt, 1, addClassToElmnt);