暂时绕过CSS转换 [英] Temporarily bypass a CSS transition

查看:58
本文介绍了暂时绕过CSS转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的风格,有一个过渡:

Let's say I have a style like this, with a transition:

#theElement {
    position: relative;
    left: 200px;
    transition: left 1s;
}

还有一些代码:

var element = document.getElementById("theElement");

function animateX(px) {
    element.style.left = px + "px";
}

所以,只需要 animateX 函数,简单地说它的作用,动画 theElement 的左边,现在如果我希望有一个函数即时设置左属性,没有转换:

So, simply there is a animateX function, which simply says what it does, animates the left propery of theElement, now what if I also want to have a function that instantly sets the left property, without a transition:

function setX(px) {
    element.style.transition = "none";
    element.style.left = px + "px";
    element.style.transition = "left 1s";
}

为什么这不起作用以及如何解决?

Why doesn't this work and how do I fix it?

推荐答案

为了使这项工作,您需要通过在JS中读取它们来刷新CSS更改。这个问题的答案解释了这是如何工作的:

In order to make this work, you need to flush the CSS changes by reading them in the JS. The answer to this question explain how this works:

我可以使用javascript强制浏览器刷新任何待处理的布局更改?

下面的工作示例:

var element = document.getElementById("theElement");

function animateX(px) {
    element.style.left = px + "px";
}

function setX(px) {
    element.style.transition = "none";
    element.style.left = px + "px";
    // apply the "transition: none" and "left: Xpx" rule immediately
    flushCss(element);
    // restore animation
    element.style.transition = "";
}

function flushCss(element) {
  // By reading the offsetHeight property, we are forcing
  // the browser to flush the pending CSS changes (which it
  // does to ensure the value obtained is accurate).
  element.offsetHeight;
}

#theElement {
  position: relative;
  left: 200px;
  transition: left 1s;
  width: 50px;
  height: 50px;
  background: red;
}
.wrapper {
  width: 400px;
  height: 100px;
}

<div class="wrapper">
  <div id="theElement"></div>
</div>
<button onclick="animateX(100)">Animate 100</button>
<button onclick="setX(0)">Set 0</button>

这篇关于暂时绕过CSS转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆