【问题标题】:Apply random value to animation-duration using jQuery使用 jQuery 将随机值应用于动画持续时间
【发布时间】: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 被预先添加到容器中 - 如果有人有解决方案,我将非常感谢。

【问题讨论】:

    标签: jquery css animation


    【解决方案1】:

    animation-delayanimation-time 需要与一个单元关联。使用以下命令将s(秒)添加到值中。这使得 css 有效。

    element.css({
      'animation-duration': animationTime + 's',
      'animation-delay': animationTime + 's'
    });
    

    另外,如果您希望隐藏其绝对定位的子项,则需要将动画容器设置为 position: relative

    Here's a fork of your pen with the changes.

    【讨论】:

      【解决方案2】:

      我通过将position:relative 添加到该元素解决了overflow:hidden 问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-07
        • 2023-03-23
        • 1970-01-01
        • 2019-07-20
        • 1970-01-01
        • 2014-05-16
        • 1970-01-01
        • 2013-01-18
        相关资源
        最近更新 更多