之前一直用 jQuery,最近开发移动端较多,转用 zepto,多数场景下都与 jQuery 无缝切换,但某些功能暂时还不支持,其中就包括我要用到的 slideDown 和 slideUp。

主要思路是通过 animate 控制元素的高度,overflow: hidden,动画结束时清空临时样式,在 callback 中操作元素的类或者进行其他操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
(function ($) {
$.fn.slideDown = function (duration, callback) {
var position = this.css('position');
this.show();
this.css({
position: 'absolute',
visibility: 'hidden'
});
var height = this.height();
this.css({
position: position,
visibility: 'visible',
overflow: 'hidden',
height: 0
});
var that = this;
this.animate({
height: height
}, duration, "linear", function() {
that.removeAttr("style");
callback();
});
};

$.fn.slideUp = function (duration, callback) {
var that = this;
var height = this.height();
this.css({
overflow: 'hidden',
height: height
});
this.animate({
height: 0
},duration, 'linear', function () {
that.removeAttr("style");
callback();
});
};
})(Zepto);

参考: