CSS 与纯 JS 的过渡无延迟

Gri*_*ief 1 javascript css css-transforms

我想要实现的是从 js 两次更改某些属性(background-color在上面的代码中),以便在它们之间运行转换,但不会从前一个状态到第一个状态。上面的代码几乎从不工作,因为超时设置为零,当它至少设置为 10 时,它几乎总是工作,当我将其设置为 100 时,它总是在我的机器上工作。我还想要的是完全避免超时和以太线性运行代码或基于适当的事件回调运行代码(到目前为止我没有发现任何有用的)。

这是一个示例(也在 jsFiddle 上):

var outter = document.getElementById('outter');
var test = document.getElementById('test');

test.onclick = function() {
  outter.removeChild(test);
    test.style.backgroundColor = 'green'
  outter.appendChild(test);
  setTimeout(function() {
    test.style.backgroundColor = 'red'
  }, 0);
}
Run Code Online (Sandbox Code Playgroud)
#test {
  position: fixed;
  left: 2em;
  right: 2em;
  top: 2em;
  bottom: 2em;
  background-color:red;

  transition-duration: 2s
}
Run Code Online (Sandbox Code Playgroud)
<div id=outter>
  <div id=test></div>
</div>
Run Code Online (Sandbox Code Playgroud)

小智 5

没有超时:

var outter = document.getElementById('outter');
var test = document.getElementById('test');

test.onmousedown= function() {
    test.style.transitionDuration = "0s";
    test.style.backgroundColor = 'green';
};

test.onmouseup= function() {
    test.style.transitionDuration = "2s";
    test.style.backgroundColor = 'red';
};
Run Code Online (Sandbox Code Playgroud)
#test {
  position: fixed;
  left: 2em;
  right: 2em;
  top: 2em;
  bottom: 2em;
  background-color:red;
}
Run Code Online (Sandbox Code Playgroud)
<div id=outter>
  <div id=test></div>
</div>
Run Code Online (Sandbox Code Playgroud)