2017-04-04 92 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"); 
});