if语句被其他语句卡住了

if statement gets stuck at else

本文关键字:语句 其他 if      更新时间:2023-09-26

我正试图通过点击同一个单词来显示和消失菜单。我刚开始学习这些语言。但我认为我正在取得一些进展。在阅读了很多关于这里和其他在线来源后,我发现了这一点:

var main = function() {
if($('.menu').css('top') == '-65px') {    
    $('.icon-menu').click(function() {
        $('.menu').animate({top: '10px'}, 400);
        $('.content').animate({top: '10px'}, 400);
    });
}
else {
    $('.icon-menu').click(function() {
        $('.menu').animate({top: '-65px'}, 400);
        $('.content').animate({top: '-65px'}, 400);
    });
}  
};
$(document).ready(main);

到目前为止,我可以让菜单出现,但不会消失。

谁能帮我?

您只检查菜单状态一次,而不是每次单击。把事情翻过来:

var main = function() {
  $('.icon-menu').click(function() {
    if ($('.menu').css('top') == '-65px') {    
      $('.menu').animate({top: '10px'}, 400);
      $('.content').animate({top: '10px'}, 400);
    } 
    else {
      $('.menu').animate({top: '-65px'}, 400);
      $('.content').animate({top: '-65px'}, 400);
    }
  });
};

您在绑定事件时检查菜单的位置,因此始终会有一个或另一个事件处理程序将被绑定,并且在处理事件时不会更改。

使用一个事件处理程序,并在事件发生时检查位置:

$('.icon-menu').click(function() {
  if($('.menu').css('top') == '-65px') {    
    $('.menu').animate({top: '10px'}, 400);
    $('.content').animate({top: '10px'}, 400);
  } else {
    $('.menu').animate({top: '-65px'}, 400);
    $('.content').animate({top: '-65px'}, 400);
  }
});