我正在尝试编写一小段代码,其中我在一个大的内部有一堆div,我想要一个名为“focus”的类首先放到第一个div,然后在5秒后切换到下一个,等等。我也想让它成为可循环的。
这是我的HTML代码:
<div class="rowwrapper">
<div class="flipcontainer">
<div class="card focused">
Content
</div>
</div>
<div class="flipcontainer">
<div class="card">
Content
</div>
</div>
<div class="flipcontainer">
<div class="card">
Content
</div>
</div>
etc…
</div>
我自己开始使用JS代码,但它似乎与我合作。
$(function() {
setInterval(function() {
$(".rowwrapper").next(".card").toggleClass("focused");
}, 5000)
});
答案 0 :(得分:2)
$.fn.circularFocus = function(interval, focusClass) {
if (typeof interval === 'undefined') interval = 1000;
if (typeof focusClass === 'undefined') focusClass = 'focused';
var cards = this.toArray();
var idCurrentFocusedCard = 0;
window.setInterval(function () {
$(cards[idCurrentFocusedCard]).removeClass(focusClass);
idCurrentFocusedCard = idCurrentFocusedCard === cards.length ? 0 : idCurrentFocusedCard + 1;
$(cards[idCurrentFocusedCard]).addClass(focusClass);
}, interval);
return this;
};
$('.card').circularFocus(5000);
答案 1 :(得分:0)
您没有访问正确的DIV容器。 $(“。rowwrapper”)。next('。card')将尝试找到“rowwrapper”的下一个兄弟DIV。您是从上一个容器中删除该类吗?
$(function() {
var i = setInterval(function() {
$(".rowwrapper").children().next(".card").addClass("focused");
}, 5000)
});
答案 2 :(得分:0)
我想我得到了你想做的事。试试这个:
$(function() {
setInterval(function() {
// get currently focused card, also remove focused class
var current = $('.rowwrapper .focused').removeClass('focused'),
// attempt to get next card in line by going to current card's parent
// then going to the next card parent and grab its inner card
next = current.closest('.flipcontainer').next('.flipcontainer:first').find('.card');
// this simply checks if next is set, if not, let's grab the first one again
if (!next.length) next = $('.rowwrapper .flipcontainer:first .card');
// add focused class to new card
next.addClass('focused');
}, 1000);
})
答案 3 :(得分:0)
您可以尝试此操作(Example Here)
$(function(){
var divs = $('div.rowwrapper').children(), i = 0;
$(divs[i]).find('.card').addClass('focused');
setInterval(function(){
$('.card').removeClass('focused');
i = i+1 <= divs.length-1 ? i+1 : 0;
$(divs[i]).find('.card').addClass('focused');
}, 5000);
});