添加/删除类和动画元素的不同方法

A different approach to add/remove classes and animate elements

本文关键字:方法 元素 动画 删除 添加      更新时间:2023-09-26

我有 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/

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');
});

演示