Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k 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 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...