代码之家  ›  专栏  ›  技术社区  ›  Tonald Drump

“跳转”到translatey值,然后动画返回0

  •  2
  • Tonald Drump  · 技术社区  · 7 年前

    我需要一个元素来“跳”到 translateY 价值 没有过渡 然后马上 使有生气 返回 translateY: 0 .

    不幸的是,以下操作不起作用(什么都没有发生,因为我想转换被“太快”删除)

    $('div').css('transform', 'translateY(' + height + 'px)');
            .addClass('animate-transform')
            .removeAttr('style');
    

    以下是可行的,但感觉很糟糕,我想知道是否有更优雅的解决方案。

    $('div').click(function() {
      
      var height = 200; // This is not always 200
    
      $('div').css('transform', 'translateY(' + height + 'px)');
      
      setTimeout(function() {
        $('div').addClass('animate-transform')
                .removeAttr('style');
      }, 0)
    
      setTimeout(function() {
        $('div').removeClass('animate-transform');
      }, 1000)
    
    })
    div {
      height: 100px;
      background-color: red;
    }
    
    .animate-transform {
      transition: transform 1s;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div></div>
    2 回复  |  直到 7 年前
        1
  •  1
  •   Temani Afif    7 年前

    您可以尝试使用CSS动画并依赖 animationend 移除类的事件。如果希望转换值是动态的,也可以使用CSS变量。

    $('div').click(function() {
      $('div').css('--v', '200px');
      $('div').addClass('animate-transform').on('animationend', function() {
        $('div').removeClass('animate-transform')
      });
    })
    div.e {
      height: 100px;
      background-color: red;
      display: block;
    }
    
    .animate-transform {
      animation: change 1s;
    }
    
    @keyframes change {
      from {
        transform: translateY(var(--v));
      }
    }
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <div class="e"></div>
        2
  •  0
  •   samuellawrentz    7 年前

    您可以使用jquery的动画API,而不是使用CSS转换。只需将DIV的位置设置为 relative 并修改 top . 工程与预期类似。

    var height = 150;
    $('div').on('click', function(){
    $('div').css('top', height).animate({'top': 0},800);
    });
    div {
          height: 100px;
          background-color: red;
      position:relative;
        }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div></div>

    参考jquery动画: https://api.jquery.com/animate/