0

我正在尝试编写一小段代码,其中我在一个大的里面有一堆 div,我希望首先将一个名为“focused”的类放在第一个 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)
});
4

4 回答 4

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);
于 2013-11-04T20:31:24.713 回答
0

您没有访问正确的 DIV 容器。$(".rowwrapper").next('.card') 将尝试定位“rowwrapper”的下一个兄弟 DIV。您是否要从以前的容器中删除该类?

$(function() {
  var i = setInterval(function() {
     $(".rowwrapper").children().next(".card").addClass("focused");
  }, 5000)
});
于 2013-11-04T20:29:09.383 回答
0

你可以试试这个(例子在这里

$(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);
});
于 2013-11-04T20:40:04.887 回答
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);
})

随机的乐趣

于 2013-11-04T20:34:54.890 回答