gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 12:09:10 29 4
gpt4 key购买 nike

我有一个 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com