问题描述
由于某种原因,此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>
解决方法
您的“错误”-您将if
语句放入设置器 .css( propertyName,value )
(也设置值...),而不是 Getter .css( propertyName )
(获取 ...的价值)。
if($("#drawer").css('margin-top') == "-5px"){
console.log("Do something");
}
-
jQuery CSS()
get
文档:https://api.jquery.com/css/#css1 -
相关文章:https://riptutorial.com/jquery/example/11775/css---getters-and-setters
基本摘要:
$(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>