简体   繁体   English

为什么如果在javascript中其他方法不起作用?

[英]Why if else doesn't work here in javascript?

I want an animation such that it toggles to slide the div left and right every time I click button. 我想要一个动画,以便每次单击按钮时都可以左右滑动div。 However, when I actually use the code it only slides it to right once and stops working any more. 但是,当我实际使用该代码时,它只会向右滑动一次并停止工作。

<script> 
var left = 1;

$(document).ready(function(){
$("button").click(function(){

  if(left==1){
    $("div").animate({left:'250px'});
    left=2;
  }else{ 
    $("div").animate({right:'250px'});
    left=1;
  }

  });
});

</script> 

What's wrong with this code? 此代码有什么问题? I couldn't think of a problem. 我没想到有问题。

Because you're using both left and right, try this: 由于您同时使用左右,请尝试以下操作:

if( left === 1 ) {
    $("div").animate({left:'250px'});
    left = 2;
}
else { 
    $("div").animate({left:'0px'});
    left = 1;
}

The loop was right, but the css wasn't. 循环是正确的,但是css是错误的。

<script> 
var left = 1;

$(document).ready(function(){
$("button").click(function(){
  if(left==1){
    $("div").animate({left:'250px'});
    left=2;
  }
  else { 
    $("div").animate({left:'0px'});
    left=1;
  }
 });
});

</script>         

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM