0

基本的に、ボタンをクリックするたびに、2 つの異なるクリック機能を切り替えようとしています。

jqueryコードは次のとおりです。

$("button").click(function () {
    $("#sidebar").animate({ width: '0px' }, 250, function() {
            $(this).hide();
         });
    $("#tabs_container").animate({
        width: "100%"
    }, 500);
    $("#tabs_container ul.tabs li a").animate({
        width: "247px"
    }, 500);
    $("#myElement_wrapper").animate({
        width: "970px"
    }, 500);
});
$("button").click(function(){
    $("#sidebar").show().animate({
        width: "219px"
    }, 500);
    $("#tabs_container").animate({
        width: "781px"
    }, 500);
    $("#tabs_container ul.tabs li a").animate({
        width: "190px"
    }, 500);
    $("#myElement_wrapper").animate({
        width: "720px"
    }, 500);
}); 

ありがとう

4

2 に答える 2

2

要素が現在「奇数」または「偶数」クリックのどちらにあるかを記憶するフラグを設定できます。

$("button").click(function() {
    var $this = $(this),
        flag = $this.data("clickflag");
    if (!flag) {
        // first code here
    } else {
        // second code here
    }
    $this.data("clickflag", !flag);
});

デモ: http: //jsfiddle.net/KHLdr/

これは、jQueryの.data()メソッドを使用して、クリックされた要素に対してブール値を格納します。

于 2013-01-20T05:06:12.930 に答える
2

それtoggleがそのためです。作成した 2 つの関数を渡します。

$("button").toggle(function () {
    $("#sidebar").animate({ width: '0px' }, 250, function() {
       $(this).hide();
    });
    // the rest of your first animation sequence
}, function () {
    $("#sidebar").show().animate({
        width: "219px"
    }, 500);
    // the rest of your second animation sequence
});

セレクターのキャッシュも検討する必要があります...


jQuery 1.9 以降を使用している場合は、独自のフラグを保持する必要があります。

$("button").click(function () {
    var toggle = $.data(this, 'clickToggle');

    if ( toggle ) {
        // your first animation sequence
    } else {
        // your second animation sequence
    }

    $.data(this, 'clickToggle', ! toggle);
});
于 2013-01-20T04:59:15.087 に答える