2017-04-04 50 views
0

我有一個框和一個旋轉css動畫應用於,我想添加一個js函數,當動畫結束時給我一個警報,我該如何使用webkitTransitionEnd做到這一點?js警告,告訴css動畫結束

這裏是我的代碼:

.box { 
 
    background: red; 
 
    position: absolute; 
 
    padding: 100px; 
 
} 
 
.box:hover { 
 
    animation-name: rotate; 
 
    animation-duration: 2s; 
 
    animation-iteration-count: infinite; 
 
    animation-timing-function: linear; 
 
} 
 
@keyframes rotate { 
 
    from { 
 
    transform: rotate(0deg); 
 
    } 
 
    to { 
 
    transform: rotate(360deg); 
 
    } 
 
}
<html> 
 
<body> 
 
    <div class="box"> 
 
    </div> 
 
</body> 
 
</html>

回答

2

它實際上是不可能的CSS,但因爲你的動畫是無限hover事件觸發,你可以聽mouseleave事件(元素不再徘徊時動畫停止)。

$('.box').mouseleave(function() { 
 
    console.log('animation has ended'); 
 
});
.box { 
 
    background: red; 
 
    position: absolute; 
 
    padding: 100px; 
 
} 
 

 
.box:hover { 
 
    animation-name: rotate; 
 
    animation-duration: 2s; 
 
    animation-iteration-count: infinite; 
 
    animation-timing-function: linear; 
 
} 
 

 
@keyframes rotate { 
 
    from {transform: rotate(0deg);} 
 
    to {transform: rotate(360deg);} 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="box"></div>

+0

取決於雖然,懸停觸發動畫,但鼠標可以在動畫之前離開是完全 –

+0

@SterlingArcher要看你怎麼用*動畫的意思是完成*。我猜它剛剛結束時就已經完成了*(鼠標離開了元素)。但情況會非常相反,如果只有動畫不是*無限的*。 –

0

實際上,你可以對事情已完全動畫添加事件偵聽器。該事件被稱爲animationend。假設你是開放的使用JavaScript,你可以這樣做:

var x = document.getElementByClass("box"); 

// Code for Chrome, Safari and Opera 

x.addEventListener("webkitAnimationEnd", function(){ 
    console.log("event had ended"); 
}); 

// Standard syntax 

x.addEventListener("animationend", function(){ 
    console.log("event had ended"); 
});