2017-02-27 91 views
0

我需要傳遞HTMl樣式中的隨機數字,該數字附加到旋轉的圖形上。即使經過努力,我也無法做到這一點。以下是我寫的代碼,但沒有效果。以HTML格式傳遞隨機值

<script> 
    @ViewBag.angle = (Math.floor(Math.random()* (5 - 1)+1))+deg; 
</script 
<style> 
    keyframes service-level{100%{transform:rotateZ(@ViewBag.angle);}}  
</style> 

如果我使用下面的靜態值代碼,它工作正常。請指教。

keyframes service-level{100%{transform:rotateZ(90deg);}} 
+0

喜,看到這一點:http://stackoverflow.com/questions/18481550/how-to-dynamically-create-keyframe-css-animations – helb

回答

0

除非你使用一些模板語言,它取代@ -keywords與價值觀,瀏覽器(或CSS解析器)不知道如何處理@ViewBag.angle

您需要通過JavaScript注入風格:

var style = document.createElement("style"); 
var angle = (Math.floor(Math.random() * (5 - 1) + 1)) + "deg"; 
style.type = "text/css"; 
style.innerHTML = "@keyframes service-level {100% {transform: rotate(" + angle + ");}}"; 
document.head.appendChild(style); 

而且在使用CSS動畫的名稱(鏈接.css文件或內聯,此處無關緊要):

div { 
    animation-name: service-level; 
    animation-duration: 3s; 
    animation-fill-mode: forwards; 
} 

Codepen example here

如果你想擁有許多隨機旋轉的元素transition將是一個更好的選擇:

[].forEach.call(divs, function(div) { 
    var angle = (Math.floor(Math.random() * (5 - 1) + 1)) + "deg"; 
    div.style.transform = "rotate(" + angle + ")"; 
}); 

CSS:

div { 
    transform: rotate(0deg); 
    transition: all 3s; 
} 

Codepen example here

+0

尊敬的人的稱呼....你是古魯! –