简体   繁体   English

jquery animate - 返回原始位置

[英]jquery animate - return to original position

I have a jquery animate that moves a div when a button is clicked: 我有一个jquery动画,当单击一个按钮时会移动div:

<script> 
$(document).ready(function(){
    $("#toggle1").click(function(){
        $("#holder").animate({right: '0px'});
    });
});
</script>

If the button is clicked again I want to be able to return this back to the original opition 如果再次单击该按钮,我希望能够将其返回到原始选项

$("#holder").animate({right: '-250px'}); // off the screen

Is there a simple way of doing this or should I be trying to implement an if statement based on a variable state? 是否有一种简单的方法可以执行此操作,还是应该尝试基于变量状态实现if语句?

you have 2 ways 你有两种方法

1st: use boolean for that 1st:使用布尔值

<script> 
$(document).ready(function(){
    var toggeled = true;
    $("#toggle1").click(function(){
      if(toggeled == true){
        $("#holder").animate({right: '0px'});
        toggeled = false;
      }else{
        $("#holder").animate({right: '-250px'});
        toggeled = true;
      }
    });
});
</script>

2nd: check for right 第二:检查是否正确

$(document).ready(function(){
    $("#toggle1").click(function(){
      if(parseInt($("#holder").css('right')) == 0){
        $("#holder").animate({right: '-250px'});
      }else{
        $("#holder").animate({right: '0px'});
      }
    });
});

I think that's quite easy: 我觉得这很容易:

<script type="text/javascript"> 
$(function(){
    var rightPos=0;
    $("#toggle1").on('click',function(e){
        e.preventDefault();
        $("#holder").animate({'right': rightPos+'px'});
        rightPos = rightPos == 0 ? -250 : 0;
    });
});
</script>

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

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