为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

隔江千里 2023-03-18 16:18:07
由于某种原因,这个 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>
查看完整描述

1 回答

?
千巷猫影

TA贡献1829条经验 获得超7个赞

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>


查看完整回答
反对 回复 2023-03-18
  • 1 回答
  • 0 关注
  • 78 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信