1

I stumbled upon an interesting example where a loop is created involving 4 div's http://jsfiddle.net/w5YHY/2/

var $elements = $('#One, #Two, #Three, #Four');
    $elements.eq(i).fadeIn(1000, function() {
        var $self = $(this);
        setTimeout(function() {
            $self.fadeOut(1000);
            anim_loop((i + 1));
        }, 3000);
    });

The loop works fine.

I had the following queries in my mind.

Each radio button corresponds to a div. If the loop is at position 3, radio 3 should be selected and so on. How is this done? Vice-versa the radio should manipulate the loop, something like a 2-way binding.

Moreover clicking the left and right buttons should also change the loop. So assume the loop is at position 3 and the left button is clicked, it should go back to 2.

How can I do all these event bindings elegantly without repeating code?

4

1 回答 1

1

尝试

<button id="left" data-dir="-1">Left</button>
<button id="right" data-dir="1">right</button>

然后

var $elements = $('#One, #Two, #Three, #Four');
var $radios = $('input[name="op"]');

var timer;
function anim_loop(index) {
    if(timer){
        $elements.filter('.current').stop(true, true).hide().removeClass('current');
        clearTimeout(timer)
    }
    $radios.eq(index).prop('checked', true);
    $elements.eq(index).stop(true, true).addClass('current').fadeIn(1000, function() {
        var $self = $(this);
        timer = setTimeout(function() {
            $self.fadeOut(1000).removeClass('current');
            anim_loop((index + 1) % $elements.length);
            timer = undefined;
        }, 3000);
    });
}

$radios.click(function(){
    anim_loop($radios.index(this));
});

$('#left, #right').click(function () {
    var index = $elements.index($elements.filter('.current')) + $(this).data('dir');
    anim_loop(index % $elements.length)
})

anim_loop(0); // start with the first element

演示:小提琴

于 2013-11-14T17:20:47.630 回答