【问题标题】:Changing attribute value in CSS with a random number generator使用随机数生成器更改 CSS 中的属性值
【发布时间】:2017-02-14 23:35:05
【问题描述】:

我正在尝试在下面的 css 代码中随机更改 animation-duration 属性(从 0 到 1)。

@keyframes blink {
   50% { border-color: #ff0000; }
}
p{
    animation-name: blink ;
    animation-duration: 0.1s ;
    animation-timing-function: step-end ;
    animation-iteration-count: infinite ;
    animation-direction: alternate ;
}

HTML

<div id="label_div">
    <p id="label" class = "blink">Player #</p >
</div>

到目前为止没有使用 Javascript,我愿意使用它。 关于如何做到这一点的任何想法?我查看了this question,但我不知道如何解决我的问题。

【问题讨论】:

  • 你的意思是你是否愿意使用Javascript?我看不出没有它怎么可能。
  • 是的,我愿意使用 Javascript

标签: javascript html css


【解决方案1】:

你的动画不适合我,但我认为这应该可以工作

const label = document.querySelector("p");
label.style.animationDuration = Math.random() + "s";

Math.random() 将返回一个介于 0-1 之间的数字。 http://www.w3schools.com/jsref/jsref_random.asp

顺便说一句,要修复您的动画,只需将 border: solid #000; 添加到您的 PC 中

【讨论】:

    【解决方案2】:

    使用以下方法确定一个介于 0 和您的时间上限之间的随机数:

    var rnd = Math.Random() + UPPERLIMIT;
    

    将该代码放入一个函数中,并使其在计算出的随机延迟后自行执行:

    function randomTimer(){
        var rnd = Math.Random() + UPPERLIMIT;
        setTimeout(randomTimer, rnd);
    }
    

    然后,只需确保在每个周期都将延迟应用于您的元素。

    function randomTimer(){
        var rnd = Math.Random() + UPPERLIMIT;
        var el = document.querySelector("p");
        el.style.animationDuration = rnd + "s";
        setTimeout(randomTimer, rnd);
    }
    

    这将每次以随机持续时间循环您的动画。

    【讨论】:

      猜你喜欢
      • 2016-03-18
      • 1970-01-01
      • 2018-03-10
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多