Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
825 views
in Technique[技术] by (71.8m points)

奇怪的动画,代码如下

https://codepen.io/779102260/...

<!DOCTYPE html>
<html>
<head>
<style>
body {
  height: 500px;
} 
div
{
  width:100px;
  height:100px;
  background:blue;
  position: relative;
  left: 0;
}
.transition {
  transition:left 2s;
}
/*div:hover
{
  left: 500px;
}*/
</style>
</head>
<body>

<div id="ttt" class=" transition" onclick="move()"></div>

<p >请把鼠标指针移动到蓝色的 div 元素上,就可以看到过渡效果。</p>

<p><b>注释:</b>本例在 Internet Explorer 中无效。</p>

</body>
<script type="text/javascript">
function move() {
  ttt.style.left = "400px"; // 需要2s才能完成
  setTimeout(() => {
    ttt.className = ""; // 中断(假设此使滚动了200px)
    ttt.style.top = "50px"; // top立即到50px,left表现无法理解
    // 如果没有下面的动画left立即到400
    // 但有这段代码left并没有立即到400px,而是看起来似乎剩余的left 200px被忽略了,然后从200过渡到800,为什么???
    setTimeout(() => {
      ttt.className = "transition"; // 重新开启动画
      ttt.style.left = "800px"; //
    });
  }, 500);
}
</script>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

浏览器渲染机制造成的,浏览器会批处理DOM的更新操作。可以增加个浏览器强制更新的操作:

console.log(ttt.offsetWidth); // 强制浏览器更新渲染
setTimeout(() => {
    ttt.className = "transition"; // 重新开启动画
    ttt.style.left = "800px"; //
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...