css - 为动态生成的 HTML 标签添加不同的动画延迟

标签 css css-animations

我有一个 HTML 页面,它可以生成任意数量的 <div></div>标签。

我想为每个 div 添加不同的动画延迟,例如:

对于 HTML 结构:

<div></div>
<div></div>
<div></div>
<div></div>

CSS 是

div:nth-child(1) {
    animation-delay: 1s;
}

div:nth-child(2) {
    animation-delay: 2s;
}

div:nth-child(3) {
    animation-delay: 3s;
}

div:nth-child(4) {
    animation-delay: 4s;
}

现在没有 Javascript 的帮助,CSS 是否提供了任何函数可以更容易地对任意随机数 div 执行相同的操作? ?

我避免使用 jQuery 因为 each() 的性能很穷。

或者当生成元素数量的上限未知时,是否有任何纯 CSS 替代方案来延迟动画?

最佳答案

不幸的是,纯 CSS 中没有。

由于您根本不是在寻找 Javascript 解决方案,您可能喜欢的一种选择是使用 CSS 预处理器,如 SASS 或 LESS 等。

SASS 代码:

$selector: div !default

@for $i from 1 through 4
  .#{$selector}:nth-child(#{$i})
    animation-delay: $i + "s"

生成的 CSS 代码:

.div:nth-child(1) {
  animation-delay: "1s";
}

.div:nth-child(2) {
  animation-delay: "2s";
}

.div:nth-child(3) {
  animation-delay: "3s";
}

.div:nth-child(4) {
  animation-delay: "4s";
}

另请参阅:can I write a loop for css

但是,如果您不想生成未知数量的 CSS 规则,请参阅下面的评论。您可以在没有 jQuerys .each 甚至没有元素样式的情况下使用 javascript。

Javascript 代码:

// function wrapper for inserting rules in stylesheets
function addCSSRule(sheet, selector, rules, index) {
  if(sheet.insertRule) {
    sheet.insertRule(selector + "{" + rules + "}", index);
  } else {
    sheet.addRule(selector, rules, index);
  }
}

// is dom loaded
document.addEventListener("DOMContentLoaded", function() {  
    var divs = document.getElementsByTagName("div"); // get all the divs
    var i = divs.length;
    for (i; i > 0; i--) {
      var selector = "div:nth-child(" + i + ")"; // setup selector
      var rule = "animation-delay: " + i + "s" 
      addCSSRule(document.styleSheets[0], selector, rule); // insert rule in first stylesheet.
    }   
});

这是两种解决方案的代码笔示例:http://codepen.io/Type-Style/pen/PZvJWz

参见 https://davidwalsh.name/add-rules-stylesheets了解更多详情。

关于css - 为动态生成的 HTML 标签添加不同的动画延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35500258/

相关文章:

css - Div 使图像上的链接不可点击

javascript - 如何在生成的 contentEditable div 的顶部和底部附加固定的不可编辑内容?

css - Google 网络字体无法在 FF 4.0 或 IE9 中加载

css - 正确旋转动画所需的透视

CSS 动画 : How do I apply transform after every iteration?

css - 用于悬停的平滑效果 CSS 动画

css - 如何对齐父div中的文本

asp.net - 在 css :hover as a background image 中请求时如何提供文件

performance - CSS3 动画和性能 : are there any benchmarks?

html - 页面打开时的CSS动画