当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - Animate click toggle

问题描述:

I animate a div when I click (click toggle in the example).I want to animate to the initial position when I click again. (I try with a variable and an if, it does not work. Perhaps there is another easier way? or there is any mistake?)

Please check your answer here:http://jsfiddle.net/uXVxH/2/

HTML:

<div id="logo"></div>

CSS:

#logo {

position:fixed;

bottom:-40px;left: 5%;

width:70px; height:80px;

background:blue;

cursor:pointer;

}

JQUERY:

$(function(){

/* CLICK simple

$("#logo").click(function() {

$("#logo").animate({bottom: "0"}, 1200)

});

*/

/*click toggle ?*/

var hidden = true;

$("#logo").click(function() {

if (hidden) {

$("#logo").animate({bottom: "0"}, 1200);

} else {

$("#logo").animate({bottom: "-40"}, 1200);

}

state = !hidden;

});

})

网友答案:

Your example is working but you did a little mistake change state for hidden variable.

var hidden = true;
$("#logo").click(function() {
  if (hidden) {
    $("#logo").animate({bottom: "0"}, 1200);
  } else {
    $("#logo").animate({bottom: "-40"}, 1200);
  }
  hidden = !hidden;
});
网友答案:

Try this:

var hidden = true;
$("#logo").click(function () {
    var bottom = hidden ? "0" : "-40";
    $(this).stop().animate({bottom: bottom}, 1200);
    hidden = !hidden;
});

FIDDLE DEMO

网友答案:

Try this:

css

#logo {
    position:fixed;
    bottom:-40px;left: 5%;
    width:70px; height:80px;
    background:blue;
    cursor:pointer;
    transition: all 0.5s;
}

.long {
    bottom: 0 !important;
    transition: all 0.5s;
}

js

$(function(){
    $("#logo").click(function() {
        $(this).toggleClass('long');
    });
});

JS fiddle link

分享给朋友:
您可能感兴趣的文章:
随机阅读: