【问题标题】:How to reverse a jQuery animation back to original CSS properties如何将 jQuery 动画反转回原始 CSS 属性
【发布时间】:2023-03-10 20:45:01
【问题描述】:

这里有很多非常相似的问题,但我找不到我的问题的确切答案。

我是使用 jQuery .animate() 方法的新手,我想知道是否有反转动画的常用或最佳方法?

这是我想出的一个例子: Fiddle

基本上它所做的只是使用 if 语句来检查一个 CSS 属性,然后将其设置为一种状态或返回另一种状态。

$(document).ready(function () {
    $("[name=toggle]").on("click", function () {
        if ($('.box').width() < 125) {
            $(".box").animate({
                opacity: .3,
                width: "125px",
                height: "125px"
            }, 250);
        } else {
            $(".box").animate({
                opacity: 1,
                width: "100px",
                height: "100px"
            }, 250)
        }
    });
});
.box {
    background-color: lightblue;
    box-shadow: 5px 5px 10px #000000;
    width: 100px;
    height: 100px;
    display: block;
    margin: 20px auto 0 auto;
    border-radius: 25px;
}
[name="toggle"] {
    display: block;
    margin: 0 auto;
    margin-top: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button name="toggle">Animate</button>
<div class="box"></div>

这是我第一次接触 .animate() 时能够想到的,但我认为可能有更好的方法。 假设您想在悬停时制作动画,并在鼠标移离元素时反转动画。有没有办法轻松地轻松反转 jQuery 动画?我不在,我可以在 CSS 中使用 :hover 状态,但这是关于 jQuery .animate() 的假设问题。

【问题讨论】:

  • 据我所知,animate() 没有 reverse 函数,但我更多地使用 VelocityJS(它支持 reverse),值得一试跨度>
  • 看起来很酷,我要开始玩了
  • $(".yourelem").removeAttr("style");
  • 可能没有更好的方法。普通的 .css() 允许您传递一个空字符串 ('') 以从元素中删除规则(因此恢复到样式表),但这似乎不适用于 .animate()

标签: javascript jquery html css animation


【解决方案1】:

您可以使用过渡使用纯 CSS 来做到这一点。

.animate-me {
    background-color:red;
    width:50px;
    height:50px;
    position:absolute;
    top:0;
    left:150px;
    transition:left 2s, background-color 2s;
  
}  
.animate-me:hover{
  left:0;
  background-color:blue;
}
&lt;div class="animate-me"&gt;&lt;/div&gt;

通常 css 更简单。然而,当浏览器是旧的 jquery 可能是你唯一的方式,所以我已经包含了 JQuery 方式。

function animationForward(){
  $(".animate-me").animate(
  {
    opacity: 0.25,
    left: "100",
    height: "100"
  }, 5000, function() {
    animationBackward();
  }
)}
function animationBackward(){
  $(".animate-me").animate(
  {
    opacity: 1,
    left: "50",
    height: "50"
  }, 5000, function() {
    animationForward();
  }
)}
animationForward();
.animate-me {
  width:50px;
  height:50px;
  background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="animate-me"></div>

【讨论】:

  • 谢谢!这真的很酷,我肯定会玩 CSS 过渡,但我仍然想知道用 jQuery 来做这件事
  • @jmancherje 我也提供了一个JQuery方式,动画完成时调用该函数:)
【解决方案2】:

我会结合 CSS 过渡和使用 jQuery 来切换类,如下所示:

JSFiddle

$(document).ready(function () {
    $("[name=toggle]").on("click", function () {
        $(".box").toggleClass("differentSizeBox");
    });
});

CSS:

.box {
    background-color: lightblue;
    box-shadow: 5px 5px 10px #000000;
    width: 100px;
    height: 100px;
    display: block;
    margin: 20px auto 0 auto;
    border-radius: 25px;
    -webkit-transition: all 0.25s ease-in;
    -moz-transition: all 0.25s ease-in;
    -o-transition: all 0.25s ease-in;
    transition: all 0.25s ease-in;
}
.differentSizeBox {
    opacity: .3;
    width: 125px;
    height: 125px;
}
[name="toggle"] {
    display: block;
    margin: 0 auto;
    margin-top: 15px;
}

这样您仍然可以通过单击按钮(或其他 JS 事件)来控制更改。

=====

编辑:我能想到的仅通过 JS 更改来“反转”的唯一方法是“记住”您正在更改的 CSS 属性......然后恢复到那个状态。这会很好,因为如果你原来的 .box css 改变了,它仍然可以在不改变 JS 的情况下工作

JSFiddle

$(document).ready(function () {
    $boxes = $(".box");
    var boxCss = {
        opacity: $boxes.css("opacity"),
        width: $boxes.css("width"),
        height: $boxes.css("height")
    };
    $("[name=toggle]").on("click", function () {
        if ($boxes.hasClass("changed")) {
            $boxes.animate(boxCss, 250);
            $boxes.removeClass("changed");
        } else {
            $boxes.animate({
                opacity: .3,
                width: "125px",
                height: "125px"
            }, 250);
            $boxes.addClass("changed");
        }
    });
});

======

注意: jQueryUI 有一个包含动画的toggleClass()

【讨论】:

    【解决方案3】:

    这可能是我能想到的最短方式:

    $(function() {
    
    var small = true;
    
    $('[name=toggle]').click(function() {
    
      small = !small;
    
      if (small) var properties = {opacity: 1, width: 100, height: 100};
      else properties = {opacity: .3, width: 125, height: 125};
    
      $('.box').stop().animate(properties, 250);
    });
    });
    .box {
      background-color: lightblue;
      box-shadow: 5px 5px 10px #000000;
      width: 100px;
      height: 100px;
      display: block;
      margin: 20px auto 0 auto;
      border-radius: 25px;
    }
    
    [name="toggle"] {
      display: block;
      margin: 0 auto;
      margin-top: 15px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <button name="toggle">Animate</button>
    <div class="box"></div>

    请注意,最好将.stop() 添加到动画中。否则它不会被中断,而是会开始累积点击次数(动画队列建立)。持续时间越长越明显。

    这是一个带有悬停动作的:

    $(function() {
    
    $('[name=toggle]').on('mouseenter mouseleave', function(e) {
    
      if (e.type == 'mouseenter') var properties = {opacity: .3, width: 125, height: 125};
      else properties = {opacity: 1, width: 100, height: 100};
    
      $('.box').stop().animate(properties, 250);
    });
    });
    .box {
      background-color: lightblue;
      box-shadow: 5px 5px 10px #000000;
      width: 100px;
      height: 100px;
      display: block;
      margin: 20px auto 0 auto;
      border-radius: 25px;
    }
    
    [name="toggle"] {
      display: block;
      margin: 0 auto;
      margin-top: 15px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <button name="toggle">Animate</button>
    <div class="box"></div>

    【讨论】:

      【解决方案4】:

      我最近使用的一个非常天真的解决方案是使用jQuery.fn.css(arrayOfPropertyNames) 获取动画属性的所有值并使用jQuery.fn.data 缓存它们。然后稍后再使用它们来恢复动画。

      罢工>

      $.fn.etamina = function(values) {
        var keys = Object.keys(values)
        var args = arguments
        return this.each(function() {
          var $this = $(this)
          $.extend(values, $this.data('etamina'))
          $this.data('etamina', $this.css(keys))
          $.fn.animate.apply($this, args)
        })
      }
      

      它采用与jQuery.fn.animate 相同的参数。

      • 第一次调用:它存储原始值并将元素动画到传递的properties

      • 第二次调用:它存储动画值并将元素动画到存储的原始值

      https://jsfiddle.net/jat8wdky/

      更新

      您可能会发疯并覆盖原始 jQuery.fn.animate 以缓存值:

      var $animate = $.fn.animate
      $.fn.animate = function(prop, speed, easing, callback) {
        if (!this.data('etamina')) {
          this.data('etamina', this.css(Object.keys(prop)))
        }
        return $animate.call(this, prop, speed, easing, callback)
      }
      
      $.fn.etamina = function(speed, easing, callback) {
        var prop = this.data('etamina')
        if (prop == null) {
          return this
        }
        this.data('etamina', null)
        return $animate.call(this, prop, speed, easing, callback)
      }
      

      使用$(selector).animate 照常制作动画,使用$(selector).etamina 还原。

      // Animate
      $('.foo').animate({
        top: '50%',
        left: '50%',
        width: '4em',
        height: '4em',
        marginTop: '-2em',
        marginLeft: '-2em',
        borderRadius: '50%'
      })
      
      // Revert
      $('.foo').etamina()
      

      https://fiddle.jshell.net/mk5zc1oh/

      注意,jQuery.css 不返回实际的元素偏移量和大小,只返回计算的样式

      【讨论】:

      • 这是唯一对我有用的解决方案,因为我的原始坐标是使用 calc() 创建的,我无法将动画 () 设置为 css calc() 坐标(jQuery 无法识别这一点) ,但是让它回到原始坐标应该是jQuery原生的函数!我们需要这个移植到上游!
      猜你喜欢
      • 2018-07-02
      • 2011-04-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      相关资源
      最近更新 更多