为什么变量不登记为真实,以使第二个if语句工作



我正在尝试创建一个滑块菜单,该滑块菜单从底部(页脚)向上滑到顶部,然后单击时,将其返回到底部(页脚)。我使用的第一个if语句可以正常工作的代码,它不会注册var slideup == true,因此,单击时,滑块不会返回。

这在我的JS文件上:

$(document).ready(function(){
   var sliderUp = false;
     if (sliderUp == false) {
        $("#slider").click( function(){
           $(this).animate({height:'100%'},200);
           sliderUp = true;
           console.log('pullUp');
           $('.firsts').fadeOut(100);
        }); 
     } 

 if (sliderUp == true) {
    $("#slider").click( function(){
       $(this).animate({height:'50px'},200);
       sliderUp = false;
       console.log(sliderUp);
       console.log('pullDown');
       $('.firsts').fadeIn(100);
   });  
 }
 });

这是我的CSS:

#slider{
    background: orange;
    color: white;
    height: 50px;
    text-align: center;
    position: absolute;
    bottom: 0;
    width: 100%;
 }

,而不是使代码变得复杂,否则您可以使用.toggle来满足您的要求。

$('#slider').toggle(
    function(){
        $(this).animate({height:'100%'},200);
        console.log('pullUp');
        $('.firsts').fadeOut(100);
    },
    function(){
        $(this).animate({height:'50px'},200);
        console.log('pullDown');
        $('.firsts').fadeIn(100);
    }
);

您将条件放在事件之外尝试以下操作:

$(document).ready(function() {
  var sliderUp = false;
  $("#slider").click(function() {
    if (sliderUp == false) {
      $(this).animate({
        height: '100%'
      }, 200);
      sliderUp = true;
      console.log('pullUp');
      $('.firsts').fadeOut(100);
    } else {
      $(this).animate({
        height: '50px'
      }, 200);
      sliderUp = false;
      console.log(sliderUp);
      console.log('pullDown');
      $('.firsts').fadeIn(100);
    }
  });
});