【问题标题】:How to increase css transition speed on the fly如何即时提高 CSS 转换速度
【发布时间】:2018-01-29 17:12:53
【问题描述】:

我有一个 css 过渡,我需要在某个时刻让它更快。但是添加类的通常行为不起作用。我的问题是为什么不这样做,以及如何实施。

HTML:

<a href="#" onclick="$('div').addClass('move')">move</a> |
<a href="#" onclick="$('div').addClass('faster')">faster</a>
<div></div>

CSS:

div {
  width: 100px;
  height: 100px;
  background-color: green;
  transition: all 10s;
}

.move {
  margin-left: 500px;
}

.faster {
  transition: all 1s !important;
}

代码笔: https://codepen.io/anon/pen/EQxaxX

【问题讨论】:

  • 我想你想在移动过程中点击faster?您必须使用 JavaScript 来捕获单击时的当前位置,删除较慢的转换类,将元素放置在该点的位置,然后添加较快的转换 - 可能,但不能单独使用 CSS 我不认为
  • 当你在某个时刻说,是你点击的那个时刻还是别的什么?我写了一个小 js,当你点击时它似乎可以解决问题,但不确定它是否是你要找的。​​span>
  • @Xoog 是的,这就是我需要的——当我点击链接时加快速度。

标签: jquery html css css-transitions


【解决方案1】:

这是一个类似的问题,我们不得不处理类似的情况,但它是关于减慢动画How to slow down CSS animation on hovering element without jumps?

这个想法是依靠容器的运动来产生这种加速度。因此,为了让您的动画快速沿同一方向移动容器,但不要忘记考虑移动容器也会移动初始元素的最终目的地,因此您也需要更改它。

这是一个例子:

$('.start').click(function() {
  $('.element').addClass('move');
})


$('.fast').click(function() {
  $('.container').addClass('faster');
})
.container {
  transition: all 5s linear;
}

.element {
  margin-top: 10px;
  width: 100px;
  height: 100px;
  background-color: green;
  transition: all 10s linear;
}

.move {
  margin-left: 500px;
}

.faster {
  margin-left: 300px;
}

.faster .move {
  margin-left: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="start">move</a> | <a href="#" class="fast">faster</a>
<div class="container">
  <div class="element"> </div>
</div>
<div class="element"> </div>

这个解决方案看起来很简单,因为它只依赖于一些 CSS,但它也有一些缺点。正如您在最后可能注意到的那样,过渡变慢了,这是因为容器的动画结束了,因此元素的速度又回到了它的初始值。此行为会根据点击的时刻而有所不同。

因此您可以调整这些值以使这种影响可以忽略不计,或者您可以考虑使用更复杂的 jQuery 代码来提高速度。

这是一个例子:

$('.start').click(function() {
  $('.element').addClass('move');
})


$('.fast').click(function() {
  $('.element').css('margin-left','10000px'); // we make a big value to increase speed
  setTimeout(function(){check_limit()},20);
  
})

// we test the limit and we avoid margin to go to the big value
function check_limit() {
   if(parseInt($('.element').css('margin-left')) >=500) {
      $('.element').css('margin-left','500px');
   } else {
      setTimeout(function(){check_limit()},20);
   }
}
.container {
  transition: all 5s linear;
}

.element {
  margin-top:10px;
  width: 100px;
  height: 100px;
  background-color: green;
  transition: all 10s linear;
}

.move {
  margin-left: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="start">move</a> | <a href="#" class="fast">faster</a>
<div class="element"> </div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2020-11-03
    • 1970-01-01
    • 2019-06-02
    • 2021-04-10
    • 1970-01-01
    相关资源
    最近更新 更多