【问题标题】:Javascript Get Element CSS Transition StageJavascript 获取元素 CSS 过渡阶段
【发布时间】:2015-02-26 06:21:26
【问题描述】:

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

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

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

是否可以找到 div 是否在 0% 和 50% 之间?请纯 Javascript。

【问题讨论】:

标签: javascript css css-transitions


【解决方案1】:

您可以在动画中分配一个属性并检索该属性值以了解动画阶段。例如,为 z-index 分配一个 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>

【讨论】:

  • 值得一提的是,getComputedStyle() 仅在 IE9+ 中支持
  • @JFK 但是IE8不支持动画,所以这不是问题
猜你喜欢
  • 2014-11-17
  • 1970-01-01
  • 1970-01-01
  • 2012-06-01
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
  • 2019-07-08
  • 1970-01-01
相关资源
最近更新 更多