为了账号安全,请及时绑定邮箱和手机立即绑定

如何通过 JS 检测 CSS 过渡状态并跳过它

如何通过 JS 检测 CSS 过渡状态并跳过它

慕标琳琳 2023-04-14 15:34:27
考虑这样的 div:<div id="someid"></div>它的风格:#someid {  transition: background-color 10s ease;  background-color: #FF0000;  height: 100px;  width: 100px;}#someid:hover {  background-color: #FFFFFF;}#someid如果可能的话,我希望有可能通过 JS 和/或结束动画检测状态(当前是否正在设置动画) 。我已经从这个答案中尝试过一件事:document.querySelector("#someid").style.transition = "none";但它不适用于当前的动画元素。关键是我需要检测元素现在是否正在动画,如果是,等待动画结束或立即结束,否则什么也不做我已经找到了 transitionend事件,但是使用它我无法检测到元素目前是否正在动画。
查看完整描述

1 回答

?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

您可以收听过渡事件并按需将其删除:


const el = document.getElementById('transition');

let isAnimating = false;


el.addEventListener('transitionstart', function() {

  isAnimating = true;

});


el.addEventListener('transitionend', () => {

  isAnimating = false;

});


el.addEventListener('transitioncancel', () => {

  isAnimating = false;

});


function removeTransition(checkIfRunning) {

  if (checkIfRunning && !isAnimating) {

    return;

  }


  el.style.transition = "none";

}

#transition {

  width: 100px;

  height: 100px;

  background: rgba(255, 0, 0, 1);

  transition-property: transform background;

  transition-duration: 2s;

  transition-delay: 1s;

}


#transition:hover {

  transform: rotate(90deg);

  background: rgba(255, 0, 0, 0);

}

<div id="transition">Hello World</div>

<br />

<button onclick="removeTransition(false)">Remove Transition</button>

<br />

<br />

<button onclick="removeTransition(true)">Remove Transition on if running</button>


查看完整回答
反对 回复 2023-04-14
  • 1 回答
  • 0 关注
  • 93 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信