我有一个页面生成 20 个随机大小的 div 元素并将它们放置在 div 容器内的随机位置。 使用 CSS @keyframe 动画,我可以对每个元素应用非常简单的缩放和颜色动画。
我想将每个元素的 animation-duration CSS 属性设置为一个随机数。我尝试使用 jQuery.css 方法这样做;
element.css({ 'animation-duration': animationTime, 'animation-delay': animationTime });
但这行不通。
有什么建议吗?
完整代码如下 - 示例位于 http://codepen.io/CronanGogarty/pen/ZOexMN
.animationContainer {
width: 100%;
min-height: 400px;
height: 100%;
border: 1px solid #000;
overflow:hidden;
}
.animationElement {
position: absolute;
background-color: yellow;
animation: increase infinite;
animation-direction: alternate;
}
@keyframes increase {
0% {
border-radius: 100%;
}
50% {
background-color: orange;
}
100% {
transform: scale(2);
background-color: red;
}
}
$(function () {
createRandomElements();
});
function createRandomElements() {
for (var i = 0; i < 20; i++) {
var dimensions = Math.floor(Math.random() * (60 - 10) + 10);
var width = $('.animationContainer').width();
var height = $('.animationContainer').height();
var eltop = Math.floor(Math.random() * (height - dimensions) + dimensions);
var elleft = Math.floor(Math.random() * (width - dimensions) + dimensions);
var animationTime = Math.floor(Math.random() * (5 - 2 + 1)) + 2;
var element = $('<div>', {
class: 'animationElement',
width: dimensions,
height: dimensions
});
element.css({ 'animation-duration': animationTime, 'animation-delay': animationTime });
element.offset({ top: eltop, left: elleft });
$('.animationContainer').prepend(element);
}
}
作为附加问题 - 谁能解释为什么 overflow:hidden
属性在 .animationContainer 元素上不起作用?我怀疑这是因为 .animationElement div 被添加到容器中 - 如果有人有解决方案,我将非常感激。
最佳答案
animation-delay
和animation-time
需要关联一个单位。使用以下代码向值添加 s
(秒)。这使 css 有效。
element.css({
'animation-duration': animationTime + 's',
'animation-delay': animationTime + 's'
});
作为奖励,您需要将动画容器设置为 position: relative
如果您希望它的绝对定位的 child 被隐藏。
关于jquery - 使用 jQuery 将随机值应用于动画持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38086603/