$(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>');
});
});
这会使预览屏幕改变大小并更改按钮,但是它不会执行切换的第二部分,这将调整预览的大小并将按钮的值更改为原始状态(打开)。
知道如何解决这个问题吗?
答案 0 :(得分:2)
在最新版本的jQuery中不推荐使用以这种方式使用的toggle()
函数。您必须创建自己的切换功能。此外,使用新元素替换元素时,事件处理程序将丢失:
$("#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);
});
答案 1 :(得分:0)
使用除“toggle()”之外的其他技术,这是一个完成你想要的工作小提琴。此技术使用标志通过添加和删除类来设置“打开/关闭”按钮的状态。
工作小提琴: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;}