jQuery 等待css过渡
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15617970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Wait for css transition
提问by Ricardo Neves
I am using css transitions to set the margin of one of my div. I need to know how can I wait for this effect to end so I can call other function then... Is there any way? I read some other posts on stack overflow but they all look different from my problem.
我正在使用 css 转换来设置我的一个 div 的边距。我需要知道我怎样才能等待这个效果结束,这样我就可以调用其他函数了……有什么办法吗?我阅读了一些关于堆栈溢出的其他帖子,但它们看起来都与我的问题不同。
回答by What have you tried
Try ThisSO answer
试试这个答案
The transition listner events vary in each browser, so the below function will find which listener to use and return the correct one.
每个浏览器的转换侦听器事件各不相同,因此下面的函数将找到要使用的侦听器并返回正确的侦听器。
function whichTransitionEvent(){
var t;
var el = document.createElement('fakeelement');
var transitions = {
'transition':'transitionend',
'OTransition':'oTransitionEnd',
'MozTransition':'transitionend',
'WebkitTransition':'webkitTransitionEnd'
}
for(t in transitions){
if( el.style[t] !== undefined ){
return transitions[t];
}
}
}
var transitionEnd = whichTransitionEvent();
element.addEventListener(transitionEnd, theFunctionToInvoke, false);
function theFunctionToInvoke(){
// set margin of div here
}
回答by Vinay
You could do it two ways (assuming the transition takes 1 second in each example):
您可以通过两种方式进行(假设每个示例中的转换需要 1 秒):
1.) Animate that element with jQuery.animate(instead of CSS transition):
1.) 使用jQuery.animate(而不是 CSS 过渡)为该元素设置动画:
$('#mydiv').animate({
'margin-left': '10px',
}, {
duration: 1000,
complete: function () {
// do stuff after animation has finished here
}
});
2.) Animate after a set period of time:
2.) 一段时间后动画:
window.setTimeout(function () {
// do stuff after animation has finished here
}, 1000);
EDIT: I understand that #2 is a bad solution, but I will keep this up in case other people were thinking down the same path I was.
编辑:我知道#2 是一个糟糕的解决方案,但我会坚持下去,以防其他人正在考虑与我相同的道路。