为什么变量没有注册为true才能使第二个if语句工作?

问题描述 投票:0回答:2

我正在尝试创建一个滑块菜单,从底部(页脚)向上滑动到顶部,单击时,返回到底部(页脚)。我使用第一个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%;
 }
javascript jquery navigation slideup
2个回答
0
投票

你在事件之外的条件试试这个:

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


1
投票

而不是使代码复杂化if和else你可以使用.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);
    }
);
© www.soinside.com 2019 - 2024. All rights reserved.