【发布时间】:2016-06-30 01:32:47
【问题描述】:
我有一个页面,它生成 20 个随机大小的 div 元素并将它们放置在 div 容器内的随机位置。 使用 CSS @keyframe 动画,我可以对每个元素应用非常简单的缩放和颜色动画。
我想将动画持续时间 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 被预先添加到容器中 - 如果有人有解决方案,我将非常感谢。
【问题讨论】: