2016-05-03 171 views
1

我想知道如何在沒有按鈕klick的交互的情況下在隨機位置平滑地停止我的旋轉動畫(css)。在css上停止旋轉動畫

span.glyphicon-arrow-up { 
position: absolute; 
top: 31%; 
left: 36%; 
margin:-60px 0 0 -60px; 
-webkit-animation:spin 2s linear infinite; 
-moz-animation:spin 2s linear infinite; 
animation-iteration-count: 2; 
animation:spin 2s linear infinite; 
font-size: 14.0em; 

@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } } 
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } } 
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } } 

我希望你們能幫助我。 (我不知道關於JavaScript的東西)

+0

變化無窮,以什麼都指望你需要檢查這篇文章http://www.w3schools.com/cssref/css3_pr_animation-iteration-count.asp –

+0

嘿,謝謝你的回答。但動畫不會停在隨機的位置,而不是「順利」。我想我需要Javascript來做到這一點。還是有另一個參數,我不知道在CSS中做到這一點? – iSeven

+0

它會更好,如果你可以提供一個工作jsfiddle –

回答

0

首先創建第二個CSS類來應用動畫。然後使用getComputedStyle來計算&設置元素的旋轉並在事件觸發時移除動畫類。你如何觸發該事件取決於你;爲了簡化速度,我剛剛使用了一個click事件,但您可以使用隨機生成的延遲設置超時,以在沒有任何用戶交互的情況下觸發它。我還包含了一個不支持transform屬性的瀏覽器回退功能,它只將其設置爲initial

document.querySelector("div").addEventListener("click",function(){ 
 
    this.style.transform=window.getComputedStyle(this).getPropertyValue("transform")||"initial"; 
 
    this.classList.remove("spin"); 
 
});
div{ 
 
    background:#000; 
 
    height:50px; 
 
    width:50px; 
 
} 
 
.spin{ 
 
    animation:spin 2s linear infinite; 
 
} 
 
@keyframes spin{ 
 
    to{ 
 
    transform:rotate(360deg); 
 
    } 
 
} 
 
body,html{height:100%;}body{align-items:center;display:flex;justify-content:center;}
<div class="spin"></div>

注意,我目前不安裝任何瀏覽器仍然需要transform屬性前綴的計算機上。在我的測試中,前綴屬性被翻譯成前綴爲getComputedStyle,但我不確定這是該功能的一個功能,還是因爲瀏覽器不需要前綴版本。如果您注意到這在瀏覽器中無法使用,需要transform作爲前綴,那麼您將需要提供進一步的回退。以下是編輯爲包括完整的列表中,您可能需要JavaScript函數:

document.querySelector("div").addEventListener("click",function(){ 
    var style=window.getComputedStyle(this); 
    this.style.transform=style.getPropertyValue("transform")||style.getPropertyValue("-webkit-transform")||style.getPropertyValue("-ms-transform")style.getPropertyValue("-moz-transform")||"initial"; 
    this.classList.remove("spin"); 
});