Move div onclick and back onclick

2019-08-10 00:32发布

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?

5条回答
再贱就再见
2楼-- · 2019-08-10 01:01

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楼-- · 2019-08-10 01:09

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
    });
}); 

查看更多
Anthone
4楼-- · 2019-08-10 01:09

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楼-- · 2019-08-10 01:20

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
查看更多
Summer. ? 凉城
6楼-- · 2019-08-10 01:23

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..

查看更多
登录 后发表回答