动画单击切换

时间:2013-05-14 11:13:08

标签: jquery

我点击动画div(在示例中单击切换)。我想再次单击时动画到初始位置。 (我尝试使用变量和if,它不起作用。也许还有另一种更简单的方法?或者有任何错误?)

请在此处查看答案: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;
    });

})

3 个答案:

答案 0 :(得分:3)

试试这个:

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

FIDDLE DEMO

答案 1 :(得分:1)

您的示例正在运行,但您为state变量更改了hidden

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

答案 2 :(得分:1)

试试这个:

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

相关问题