【问题标题】:Question about execution sequence with toggling CSS attributes (namely animation) [duplicate]关于切换 CSS 属性(即动画)的执行顺序的问题 [重复]
【发布时间】:2021-10-09 06:31:49
【问题描述】:

所以在这个例子中,如果我不嵌套

box.style.animation = 'myanimation 3s'

在 setTimeout 内,则代码不起作用。但是当我像这样运行它时,超时延迟为零,它可以工作。本来我以为可能是执行时间错误,所以我把 Timeout 延迟设置为 50,但我很好奇并尝试了较低的量,直到我到达零,它仍然运行。本质上,我只是想在每次单击元素时实现一个动画。有没有更好/更安全的解决方法?另外,出于好奇,在“if”语句之后直接运行该行代码与将其嵌套在延迟为 0 的 setTimeout 中有何区别?我正在使用 Firefox 和 Ubuntu LTS 20.04

编辑:我应该补充一点,如果我不嵌套在 setTimeout 函数中,动画将第一次运行,但不会在任何后续时间运行。但是当我运行如图所示的代码时,它每次都会运行。enter image description here

const box = document.querySelector('.box')

box.addEventListener('click', function() {
    if(box.style.animation){
        box.style.animation = ''
    }
    setTimeout(function() {
        box.style.animation = 'myanimation 3s'
    }, 0)



})

编辑:我在 reddit 上遇到的另一个答案是监听一个 animationend 事件,例如:

const box = document.querySelector('.box')

box.addEventListener('click', function() {
    box.style.animation = 'myanimation 3s'
    })

box.addEventListener('animationend', function()  {
    box.style.animation = ''
})

【问题讨论】:

标签: javascript css


【解决方案1】:

不使用 timeout 时似乎什么都没有发生的原因是现代浏览器完全优化了第一条语句,以防止发生对性能产生负面影响的不必要操作。

浏览器注意到您将动画属性设置为空字符串,只是为了将其设置为下一行中的另一个值。这会导致回流,而且在许多情况下这不是您想要的。在这种情况下,尝试重置 CSS 动画,这正是您想要的。

所以你需要告诉浏览器故意引起回流。一种方法是使用setTimeout,因此第一个表达式不会被优化掉。另一种方法是通过做一些本身会导致回流的事情来引起回流。 offsetLeft、offsetTop、offsetWidth 和 offsetHeight 是这样的属性,它们会导致回流,以便在访问时报告准确的值。只需访问它们就足够了,无需将值放入变量或任何东西中:

const box = document.querySelector('.box')
box.addEventListener('click', function() {
  if (box.style.animation) {
    box.style.animation = ''
  }
  box.offsetLeft; // this forces a reflow, just like setTimeout
  box.style.animation = 'myanimation 3s'
})
.box {
  background: red;
  width: 120px;
  height: 120px;
  position: relative;
}

.box::after {
  content: "click me!";
  color: #fff;
  display: block;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%)
}

@keyframes myanimation {
  from {
    transform: translateY(0)
  }
  50% {
    transform: translateY(1em)
  }
  to {
    transform: translateY(0);
  }
}
<div class="box">

</div>

【讨论】:

  • 谢谢,这就是我想要弄清楚的,因为 setTimeout() 是一种导致回流的方法,所以我将保持代码不变。感谢您的意见!
猜你喜欢
  • 2018-12-09
  • 2021-08-06
  • 2022-09-28
  • 1970-01-01
  • 2021-03-31
  • 2018-05-23
  • 2019-10-17
  • 1970-01-01
  • 2013-12-25
相关资源
最近更新 更多