1

我有 5 个列表项,当单击一个时,我知道的唯一方法是为所有元素设置动画,然后将所选元素重新设置为新宽度。谁能告诉我如何减少这个过程,以便只有当前活动项目被激活并删除类,然后新项目被激活并添加活动类?

JS

var test = $('#test'),
    test_li = test.children(),
    small = 60,
    large = 200;

test_li.on('click', function(e) {

    if( !$(this).hasClass('active') ){
        test_li.animate({ width: small }, 300).removeClass('active'); //animates every single li every time
        $(this).animate({ width: large }, 300).addClass('active');
    } 

});​

小提琴在这里:http: //jsfiddle.net/TSNtu/1/

4

1 回答 1

4
var test = $('#test'),
    test_li = test.children(),
    small = 60,
    large = 200;

test_li.on('click', function(e) {

    // if clicked element is active itself then do nothing
    if ($(this).hasClass('active')) return;

    // remove active from others
    $('.active', test).animate({
        width: small
    }, 300).removeClass('active');
    // animate the clicked one
    $(this).animate({
        width: large
    }, 300).addClass('active');
});

演示

单链

var test = $('#test'),
    test_li = test.children(),
    small = 60,
    large = 200;

test_li.on('click', function(e) {

    // if clicked element is active itself then do nothing
    if ($(this).hasClass('active')) return;

    $(this) // clicked li
        .animate({
            width: large
        }, 300)
        .addClass('active')
        .siblings('.active') // other li
        .animate({
            width: small
        }, 300)
        .removeClass('active');
});

演示

于 2012-06-12T16:04:21.873 回答