为什么变量没有注册为 true 来使第二个 if 语句起作用?

Why is the variable not registering as true to make the second if statement work?

我正在尝试创建一个滑块菜单,它从底部(页脚)向上滑动到顶部,单击后返回底部(页脚)。 我的代码与第一个 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%;
 }

您将条件置于事件之外 试试这个:

$(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);
    }
  });
});

您可以使用 .toggle 来实现您的要求,而不是使用 if 和 else 使代码变得复杂。

$('#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);
    }
);