【问题标题】:How to combine many CSS animation nth-of-type selectors into one?如何将许多 CSS 动画 nth-of-type 选择器组合成一个?
【发布时间】:2017-10-18 19:54:03
【问题描述】:

鉴于大量<hr> html 元素在页面加载时应该一个接一个地改变颜色。目前动画可以工作,但是对于html中每个新添加的<hr>元素,它需要在CSS中进行大量重复的手工劳动。由于每个下一个<hr> 行的转换间隔都是相同的,这是否可以在 CSS 中以更优雅和更短的方式编写?

目标是能够添加新的 hr 元素无需每次都更改 CSS。

再次:这个问题是关于如何仅在 CSS 中做到这一点(更优雅)? (没有 js/sass/scss)

nav hr{
    border-top: 3px solid #BBB;
    border-bottom: 0px;
    margin: 10px 0;
}
	
nav hr:nth-of-type(01){animation: .5s ease 0.0s 1 gogo}
nav hr:nth-of-type(02){animation: .5s ease 0.1s 1 gogo}
nav hr:nth-of-type(03){animation: .5s ease 0.2s 1 gogo}
nav hr:nth-of-type(04){animation: .5s ease 0.3s 1 gogo}
nav hr:nth-of-type(05){animation: .5s ease 0.4s 1 gogo}
nav hr:nth-of-type(06){animation: .5s ease 0.5s 1 gogo}
nav hr:nth-of-type(07){animation: .5s ease 0.6s 1 gogo}
nav hr:nth-of-type(08){animation: .5s ease 0.7s 1 gogo}
nav hr:nth-of-type(09){animation: .5s ease 0.8s 1 gogo}
nav hr:nth-of-type(10){animation: .5s ease 0.9s 1 gogo}
nav hr:nth-of-type(11){animation: .5s ease 1.0s 1 gogo}
nav hr:nth-of-type(12){animation: .5s ease 1.1s 1 gogo}
 /* Boy this takes a lot of time for every new <hr> added in the html */

@keyframes gogo {
    0%   {border-top-color: #DDD}
    100% {border-top-color: #00F}
}
<nav>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
</nav>

JSFiddle Demo

【问题讨论】:

标签: html css animation css-selectors css-animations


【解决方案1】:

使用 less 或 scss,您可以在无需人工劳动的情况下生成 css。但它仍然远非优雅。

也许一些 CSS 天才知道一些我不知道的事情,但我看不出有什么办法可以绕过一些最小的 JavaScript:

var hrs = document.getElementsByTagName('hr');
for (var c = 0; c < hrs.length; c++) {
  hrs[c].style.animation = ".5s ease " + (c * 0.1) + "s 1 forwards gogo";
}
nav hr {
  border-top: 3px solid #BBB;
  border-bottom: 0px;
  margin: 10px 0;
}

@keyframes gogo {
  0% {
    border-top-color: #DDD
  }
  100% {
    border-top-color: #00F
  }
}
<nav>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
  <hr>
</nav>

【讨论】:

  • 感谢您的回答@Mikk3lRo!这个问题是关于如何仅在纯 CSS 中做到这一点(更优雅)! (没有 js/sass/scss)。仍然为您的答案 +1:如果不存在纯 CSS 方法,那么我会考虑您的答案。
  • 我确实理解它,我也理解将 JS 用于视觉样式的愿望。我也希望有人能提出一个纯 CSS 解决方案,因为这在许多情况下都非常有用......我只是怀疑它是否存在足以为你的(实际)问题提出这个(实际)解决方案;)跨度>
  • 谢谢队友@Mikk3lRo,你的评论激励我对我的问题悬赏(明天有资格获得悬赏)
【解决方案2】:

要使hr 保持蓝色,您可以使用forwards 作为动画填充模式,并为您需要scss 的每个div 动态增加延迟时间。 DEMO

$delay: 0.0s;

@for $i from 1 through  9 {
  hr:nth-child($i) {
    $delay = $delay + 0.1s;
    animation: .5s ease $delay 1 forwards  gogo;
  }
}

【讨论】:

  • 感谢您的回答@Nenad Vracar!这个问题是关于如何仅在纯 CSS 中做到这一点(更优雅)! (没有 js/sass/scss)。仍然为您的答案 +1:如果不存在纯 CSS 方法,那么我会考虑您的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
  • 2017-06-29
  • 1970-01-01
  • 2013-05-09
  • 2014-01-13
  • 2013-11-23
相关资源
最近更新 更多