0

アコーディオンメニューを作ろうとしていますが、小さな問題に直面しています。ポイントは、最初のパネルをクリックするとスライドが展開され、2番目のパネルをクリックすると機能するということです。しかし、もう一度開始して最初のものをクリックすると、驚き、何も起こらず、もう一度クリックすると、スライドが展開されます:D

ここに私のフィドルがあります!

$('#one').toggle(function(){
$('.content').animate({width:'42%'});
$('.content1').animate({width:'0%'});    
}, function(){ 
$('.content').animate({width:'0%'});
});


$('#two').toggle(function(){
$('.content1').animate({width:'42%'});
$('.content').animate({width:'0%'});    
}, function(){ 
$('.content1').animate({width:'0%'});
});

それは奇妙で、最初のクリックから拡大したいのですが、誰か助けてくれますか?

4

1 に答える 1

0

あなたのアプローチにはいくつかの欠陥があります。まず、これをスケーラブルにしたい場合は、クラスを再利用してください。第 2 に、jQuery は任意のコンテキストで動作するようにするため、一意の要素ではなくクラスをターゲットにする必要があります。私はあなたのhtmlを自由に調整しました:

<ul id="vertical">
    <li id="one" class="panel"></li>
    <li class="content"></li>
    <li id="two" class="panel"></li>
    <li class="content"></li>
    <li id="three" class="panel"></li>
    <li class="content"></li>
</ul>

JavaScript のアプローチは、より洗練されたものになる可能性もあります。どの要素を展開する必要があるかはわかっているので、すべての要素をチェックする必要はありません。

$('.panel').click(function(){

    //hide everything
    $(".content").stop().animate({"width": 0}, 500);

    //animate the target element to the desired width
    //because animations are asynchronous, this line will execute immediately after the first,
    //the stop() will ensure this element will immediately stop whatever animation it was doing,
    //and then animate to 42%
    $(this).next().stop().animate({"width": "42%"}, 500);       
});

実際に見る

于 2013-06-07T11:02:38.170 に答える