Javascript 第二次单击div将关闭并直接打开
我正在制作一个菜单,可以展开和折叠。当我点击它时,我的代码工作正常并折叠div。如果我再次点击open-en-close div,它也可以正常打开。但第二次这样做会直接关闭和打开我的div。有人能告诉我我做错了什么吗 $( document ).ready(function(e) { // Collapse and expand $("#collapse").click( function() { $("#information").fadeOut(200); $("#leftColumn").animate({width:"10px"}, 200); $("#collapse").html("»"); $(this).click(function() { $("#information").fadeIn(200); $("#leftColumn").animate({width:"250px"}, 200); $("#collapse").html("«"); }); } ); }); $(文档).ready(函数(e){ //崩胀 $(“#折叠”)。单击( 函数(){ 美元(“#信息”)。淡出(200); $(“#leftColumn”).animate({width:“10px”},200); $(“#折叠”).html(“»”); $(此)。单击(函数(){ $(“#信息”)。fadeIn(200); $(“#leftColumn”).animate({width:“250px”},200); $(“#collapse”).html(“«”); }); } ); });Javascript 第二次单击div将关闭并直接打开,javascript,jquery,toggle,expand,collapse,Javascript,Jquery,Toggle,Expand,Collapse,我正在制作一个菜单,可以展开和折叠。当我点击它时,我的代码工作正常并折叠div。如果我再次点击open-en-close div,它也可以正常打开。但第二次这样做会直接关闭和打开我的div。有人能告诉我我做错了什么吗 $( document ).ready(function(e) { // Collapse and expand $("#collapse").click( function() { $("#information").fa
您重写了第一个onclick函数——这就是为什么您必须稍微不同地处理扩展/折叠。此变体仅添加和删除一个类,以决定应使用哪个动画:
( document ).ready(function(e) {
// Collapse and expand
$("#collapse").click(
function() {
// default case
if(!$(this).hasClass('collapsed')) {
$(this).addClass('collapsed');
$("#information").fadeOut(200);
$("#leftColumn").animate({width:"10px"}, 200);
$("#collapse").html("»");
} else {
// and in case it is collapsed...
$(this).removeClass('collapsed');
$("#information").fadeIn(200);
$("#leftColumn").animate({width:"250px"}, 200);
$("#collapse").html("«");
}
}
);
});
试试这个
var toggle=0;
$("#collapse").click(function() {
if(toggle==1){
$("#information").fadeIn(200);
$("#leftColumn").animate({width:"250px"}, 200);
$("#collapse").html("«");
toggle=0;
}
else
{
$("#information").fadeOut(200);
$("#leftColumn").animate({width:"10px"}, 200);
$("#collapse").html("»");
toggle=1;
}
});
请提供html结构将新函数绑定到
click()
事件。它不会覆盖第一个函数,因此在第二次单击时将调用这两个函数。您可以查看toogle()
事件。唯一不起作用的是»@robert-ooops的.html更改,修复了这个问题!
var toggle=0;
$("#collapse").click(function() {
if(toggle==1){
$("#information").fadeIn(200);
$("#leftColumn").animate({width:"250px"}, 200);
$("#collapse").html("«");
toggle=0;
}
else
{
$("#information").fadeOut(200);
$("#leftColumn").animate({width:"10px"}, 200);
$("#collapse").html("»");
toggle=1;
}
});