Move div onclick and back onclick

2019-08-10 00:52发布

问题:

I have a jQuery code that moves a certain div element on right as I click it, i'd like to move it back to its original position when I click back on it.

$(document).ready(function() {
    $("#wel1").click(function() {
        $("#sidemenu").animate({left: "80px"});
    });
});    

Give me a simple example of how to achieve it?

回答1:

One possible way to achieve it is to store the state in a variable and check its state on click.

$(document).ready(function() {
   var sideMenu = false;
    $("#wel1").click(function() {
      if (!sideMenu) {
        $("#sidemenu").animate({left: "80px"});
        sideMenu = true;
      }
      else {
        $("#sidemenu").animate({left: "0px"});
        sideMenu = false;     
      }
    });
}); 

Please be aware that this solution has several issues:

  • will not work for multiple menus
  • can produce unwanted animation effects ("jumping") if quickly clicked


回答2:

You can simplify this by adding an attribute to store the current state of the div. Implemented at : http://jsfiddle.net/mwtrsw9p/

$('#movable').click(function(){
if($(this).attr("trigger")==="0"){
    $(this).animate({"left":"100px"},700);
    $(this).attr("trigger","1");
}
else{
    $(this).animate({"left":"0px"},700);
    $(this).attr("trigger","0");
}
});

HTML:

<div id = "movable" trigger = "0"></div>

CSS :

#movable{
position:relative;
height:50px;
width:50px;
background-color:red;
}


回答3:

I think this way is best:


css:

.animated_right{
    left:80px;
}

js:

$(document).ready(function() {
    $("#wel1").on("click", function() {
        $("#sidemenu").toggleClass("animated_right", 1000); // 1sec
    });
}); 



回答4:

You could do something like this:

var toggle = 1;

$(document).ready(function() {
    $("#wel1").click(function() {
    if (toggle == 1){
        $("#sidemenu").animate({left: "80px"});
toggle = 0;
    } else{
$("#sidemenu").animate({right: "80px"});
toggle = 1;
    }
    });
});

You have a variable 'toggle' with a value of 1, when you click it will check if 'toggle' equals 1, if it does it will move to the left, and then set 'toggle' to 0, because of this the first if will result false if you click a second time, and it will use the if statement and move the object to the right, after which it will set the value of 'toggle' to 1 which will result in your desired behaviour.



回答5:

You need a status to check whether it has been clicked or not, like below:

$("#wel1").click(function() {
    if($(this).hasClass("clicked")){
        $(this).removeClass("clicked");
        $("#sidemenu").animate({left: "80px"});
    }else{
        $(this).addClass("clicked");
        $("#sidemenu").animate({left: "0px"});
    }
});

Check out my fiddle..