Skip to content

Instantly share code, notes, and snippets.

@lgmcolin
Last active December 30, 2015 13:59
Show Gist options
  • Save lgmcolin/7838680 to your computer and use it in GitHub Desktop.
Save lgmcolin/7838680 to your computer and use it in GitHub Desktop.
写了个自定义transition,并且实现transition运行结束后触发callback. 效果: http://jsbin.com/ezAFaVIJ/1/edit
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<title>test</title>
<style>
body{
margin:20px;
}
.element{
width: 100px;
height: 100px;
background: red;
}
</style>
<script type="text/javascript">
var defaults = {
duration: 400,
easing:'ease'
};
//Be aware that sometimes this event doesn’t fire, usually in the case when properties don’t change or a paint isn’t triggered. To ensure we always get a callback, let’s set a timeout that’ll trigger the event manually.
$.fn.emulateTransitionEnd = function(duration){
var called = false,
$el = this;
$(this).one('webkitTransitionEnd',function(){
called = true;
});
var callback = function(){
if(!called)
$($el).trigger('webkitTransitionEnd');
};
setTimeout(callback,duration);
};
$.fn.transition = function(properties,options){
$el = $(this);
options = $.extend({},defaults,options);
properties['webkitTransition'] = 'all'+ options.duration +'ms'+ options.easing;
var callback = function(){
$el.dequeue();
if(options.complete){
options.complete.apply($el);
}
};
//用到了Jquery中的queue和dequeue
$el.queue(function(){
//webkitTransitionEnd可能不触发,写个判断emulateTransitionEnd模拟触发
$el.one('webkitTransitionEnd',callback);
$el.emulateTransitionEnd();
$(this).css(properties);
});
return this;
}
setTimeout(function(){
var callback = function(){
alert('Transition complete');
};
$('.element').transition({marginLeft: 100}).delay(1000).transition({marginTop: 200},{complete: callback });
}, 2000);
</script>
</head>
<body>
<div class="element"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment