基本的 Javascript if 语句与 Jquery 不工作

由于某种原因,这个 if 语句永远不会到达 else。当我点击#drawer-drop 时,边距会发生变化,但我无法将其改回。我没有看到任何控制台错误。


#drawer{margin-top:-600px;}


$(document).ready(function(){

  $("#drawer-drop").click(function(){

    if($("#drawer").css('margin-top','-600px')){

       $('#drawer').css('margin-top','0px');

    }else{

       $('#drawer').css('margin-top','-600px');

    }

  });

});


<nav id="drawer">

  <h1>This will be a sweet menu.</h1>

</nav>


<a id="drawer-drop">MENU</a>


隔江千里
浏览 80回答 1
1回答

千巷猫影

if你的“错误”——你在语句中放入了Setter .css( propertyName, value )(Set the value too...),而不是Getter .css( propertyName )(Get the value of...)。if($("#drawer").css('margin-top') == "-5px"){   console.log("Do something"); }基本片段:$(document).ready(function(){  $("#drawer-drop").click(function(){    console.log($("#drawer").css('margin-top'));    if($("#drawer").css('margin-top') == "-5px"){      /* Setter */      $('#drawer').css('margin-top','0px');      $('#drawer').css('background','red');    }else{     /* Setter */      $('#drawer').css('margin-top','-5px');      $('#drawer').css('background','blue');    }  });});#drawer{  margin-top: 5px;  background: red;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><nav id="drawer">  <h1>This will be a sweet menu.</h1></nav><a id="drawer-drop" href="#">MENU</a>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript