0

I'm trying to write short piece of code where I have a bunch of divs inside one big and I want a class called "focused" to first be put to the first div, then after 5 seconds toggle to next one, and so on. I'd also want this to be loopable.

Here's my HTML code:

<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>

I started with a JS code by myself, but it doesn't seem to cooperate with me.

$(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

私はあなたがやろうとしていることを理解していると思います。これを試して:

$(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 に答える
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 に答える