我有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/
答案 0 :(得分: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');
});
<强> DEMO 强>
使用单链
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');
});
<强> DEMO 强>