【问题标题】:How to make on toggle different animation to an item [closed]如何为项目切换不同的动画[关闭]
【发布时间】:2015-06-17 18:56:15
【问题描述】:

我想让左栏在您单击它时变为 CSS left 10 动画,当我再次单击它时返回默认 CSS。

我试过这段代码:

$('.left-bar').click(function() {
    $('.left-bar').toggle(function () {
        $(this).animate({
            // style change
            left: "-116x"
        }, 500);
    }, function () {
        $(this).animate({
            // style change back
            left: "-185px"
        }, 500);
    });
}

【问题讨论】:

  • 在 Stackoverflow 上你不应该使用文字说话。用完整的单词写出完整的英语句子。

标签: jquery click jquery-animate toggle


【解决方案1】:

您可以执行以下操作,而不是使用.toggle。该示例基于.animate

在示例中,我使用.data 来存储元素的状态isToggled。基于这些数据,我可以判断我是否可以进入一个状态回到之前的状态

var $leftBar = $('.left-bar');
$leftBar.click(function() {
  var isToggled = $leftBar.data('toggled'); // get data
   
  var action = isToggled ? "+=100px" : "-=100px"; 
  $leftBar.animate({ "left": action }, 500);
  
  $leftBar.data('toggled', !isToggled); // set the opposite state of current one
});
.left-bar {
  position: absolute;
  background-color: blue;
  width: 50px;
  height: 50px;
  left: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="left-bar"></div>

注意事项:

  1. 这个"left":"+=100px" 将100px 添加到现有的左变量(例如,如果left = 100 那么结果将是left += 100px = 200px)。 -=100px 表示减去 100px(例如,如果 left = 100 则结果将是 left -= 100px = 0px)。

  2. 我没有使用 .toggle(),因为它按照文档中的说明进行操作:

显示或隐藏匹配的元素

并且您想更改css元素不隐藏和显示

【讨论】:

  • 没有兄弟,我想切换点击就是这样:) 不需要所有这些 JS
  • 我无法理解这部分 var action = isToggled 吗? "+=100px" : "-=100px";
  • 我只想知道“?”这个语法:)
  • 称为三元运算符,see this
  • @Un1xCr3w 查看我的更新。
猜你喜欢
  • 1970-01-01
  • 2013-03-25
  • 1970-01-01
  • 2014-09-26
  • 2011-10-31
  • 2011-09-12
  • 2016-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多