2017-02-14 181 views
2

我試圖在下面的css代碼中隨機更改animation-duration屬性(從0到1)。使用隨機數生成器更改CSS中的屬性值

@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,但我無法弄清楚如何解決我的問題。

+0

你的意思是說你*是否願意使用Javascript?我不明白如果沒有,情況將會如何。 – lonesomeday

+0

是的,我願意使用Javascript –

回答

3

你的動畫工作不適合我,但我認爲這應該工作

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;您p CSS

1

確定一個隨機數0和你的上時限之間:

var rnd = Math.Random() + UPPERLIMIT; 

把這些代碼的功能,並在計算出的隨機延遲後自行執行:

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

然後,只要確保appl每個週期都會延誤你的元素。

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

這將循環您的動畫與隨機持續時間每次。