0
$(document).ready(function () {
    $("#button").toggle(function () {
        $("#preview").animate({
            height: 940,
            width: 940
        }, 800);
        $("#button").replaceWith('<div id="button" style="margin:50px">Close</div>');
    }, function () {
        $("#preview").animate({
            height: 500,
            width: 500
        }, 800);
        $("#button").replaceWith('<div id="button" style="margin:0px">Open</div>');
    });
});

这会使预览屏幕更改大小并更改按钮,但它不会执行切换的第二部分,这将重新调整预览大小并将按钮的值更改为原始状态(打开)。

知道如何解决这个问题吗?

4

2 回答 2

2

以这种方式使用的toggle()函数在最新版本的 jQuery 中已被弃用和删除。您必须创建自己的切换功能。此外,当用新元素替换元素时,事件处理程序会丢失:

$("#button").on('click', function() {
    var state = $(this).data('state');
    if ( state ) {
        $("#preview").animate({height: 500, width: 500 }, 800);
        state = false;
    }else{
        $("#preview").animate({height: 940, width: 940 }, 800);
        state = true;
    }
    $(this).text(state ? 'Open' : 'Close').data('state', state);
});

小提琴

于 2013-05-16T14:52:19.090 回答
0

这是一个使用“toggle()”以外的不同技术来完成你想要的工作的小提琴。该技术使用标志通过添加和删除类来设置“打开/关闭”按钮的状态。

工作小提琴:http:
//jsfiddle.net/nY6UC/2/

jQuery代码:

$(document).ready(function () {

    $("#button").on("click", function () {

        if ($(this).hasClass("close")){

            $(this).removeClass("close");
            $(this).text("open");
            $("#preview").animate({
                height: 100,
                width: 100
            }, 800);
        }else{

            $(this).addClass("close");
            $("#preview").animate({
                height: 300,
                width: 300
            }, 800);
            $("#button").text("close");
        }
    });

});

CSS:

#button, #preview{     width: 100px;    height: 100px; }
#button {     background-color: red;}
#preview{     background-color: blue;}
于 2013-05-16T15:03:53.517 回答