Javascript获取元素CSS过渡阶段

Javascript Get Element CSS Transition Stage

本文关键字:CSS 获取 元素 Javascript      更新时间:2024-05-26

是否可以使用Javascript获取对象在CSS转换的哪个阶段,而不使用间隔或依赖于开始时间戳?我知道转换可以串在一起,但如果可以的话,我宁愿避免这种情况。

例如,对于一个经历以下转换的div:

@keyframes example {
  0% {background: red;}
  50% {background: blue;}
  100% {background: yellow;}
}

是否可以确定div是否在0%和50%之间?请使用纯Javascript。

您可以在动画中指定一个属性并检索该属性值以了解动画阶段。例如,asign z索引的值在100和200之间:

单击元素以显示动画的百分比

function showStep () {
    var ele = document.getElementById("test");
    var step = getComputedStyle(ele).getPropertyValue("z-index") - 100;
    ele.innerText = step;
}
#test {
  position: absolute;
  width: 400px;
  height: 200px;
   border: solid red 1px;
   -webkit-animation: colors 4s infinite;
   animation: colors 6s infinite;
  font-size:  80px;
  color:  white;
}
@-webkit-keyframes colors {
  0% {background: red; z-index: 100;}
  50% {background: blue;  z-index: 150;}
  100% {background: yellow; z-index: 200;}
}
@keyframes colors {
  0% {background: red; z-index: 100;}
  50% {background: blue;  z-index: 150;}
  100% {background: yellow; z-index: 200;}
}  
<div id="test" onclick="showStep();">
</div>