【问题标题】:How do I add an transition animation by toggling a class?如何通过切换类来添加过渡动画?
【发布时间】:2022-01-08 17:32:41
【问题描述】:

我有一些元素需要有条件地突出显示/取消突出显示。

所以我有一个名为highlight 的类用于任何需要用过渡动画突出显示的元素。

问题是当 highlight 类被删除时我无法为它制作动画。

因为任何元素都可以突出显示,所以我找不到它们的特定选择器。

我可以这样做,但对我来说似乎不合适:

* {
  transition: background-color 1s;
}

有没有更好的方法来实现它?

这里有一个简化的例子来说明我的问题:

[...document.querySelectorAll('body *')].forEach(e => e.addEventListener('click', () => e.classList.toggle('highlight')));
.highlight {
  background-color: red;
  transition: background-color 1s;
}
<h2>Click anything to toggle highlight</h2>

<p>Hello</p>
<p>World</p>
<p>Thanks</p>

【问题讨论】:

  • 好吧,如果anything可以突出显示,你还想做什么?
  • I could do this but it just doesn't seem right to me。我认为这就是适合你的方式。怎么看起来不对劲?它正在工作
  • @HuyPhạm 这种方法的问题是我不能对其他选择器使用转换,否则它会被覆盖。
  • @HaoWu 您介意在您的 sn-p 中说明(other selectors 问题)吗?这有点误导
  • @HuyPhạm 如果我有一个.container { transition: opacity 0.5s; },那么当.container 得到类highlight 时,背景将不会被动画化。持续时间也不正确。

标签: html css css-transitions


【解决方案1】:

逻辑不同

[...document.querySelectorAll('body *')].forEach(e => e.addEventListener('click', function(e) {
  e.target.classList.toggle('bg');
  e.target.classList.add('highlight'); /* always add highlight */
}));
/* remove highlight when the transition is done */
[...document.querySelectorAll('body *')].forEach(e =>
  e.addEventListener('transitionend', function(e) {
    e.target.classList.remove('highlight');
  })
);
.highlight {
  transition: background-color 1s;
}

.bg {
  background: red;
}
<h2>Click anything to toggle highlight</h2>

<p>Hello</p>
<p>World</p>
<p>Thanks</p>

【讨论】:

  • 非常感谢! transitionend 绝对是更好的方法!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-03
  • 2021-01-29
  • 1970-01-01
  • 1970-01-01
  • 2021-07-23
  • 1970-01-01
  • 2014-10-20
相关资源
最近更新 更多