今天在测试微信小程序动画的时候遇到了坑,需求是这样的点击时子元素从外部滑动回来,父元素的高度跟随子元素的高度改变。 
实现子元素left为0并不复杂,但是改变父元素box的高度的时候却遇到了坑,因为是需要跟随子元素right的高度来改变父元素box的高度的,并且子元素right的高度不确定,我们需要先获取子元素的高度。 在改变高度的时候出错了,高度未改变。在测试时发现 1 2 3 4 5 6 7 8 9 10 | var box = wx.createAnimation(option);
var obj = wx.createSelectorQuery();
obj. select ( '.anr' ).boundingClientRect(function (rect) {
box.height(rect.height).step();
console.log(1);
}).exec();
console.log(2);
that.setData({
box: box.export()
});
|

先打印的竟然是2,原来是一个异步操作,这就可以理解为什么执行无效了。改成这样 1 2 3 4 5 6 7 | obj. select ( '.anr' ).boundingClientRect(function (rect) {
var box = wx.createAnimation(option);
box.height(rect.height).step();
that.setData({
box: box.export()
});
}).exec();
|
想着应该没问题了,但是遇到了另外一个坑,父元素的高度一下子变成了预设的效果,并没有Animation的渐变效果。本身父元素的高度是由left这个子元素撑起来的,给父元素预设一个高度这个问题就解决了。渐变效果就实现了。 源码解析 wxml1 2 3 4 5 6 | <view class = "box" animation= "{{box}}" >
<view class = "anl" >left</view>
<view class = "anr" animation= "{{anr}}" >right</view>
</view>
<button bindtap= "add" wx: if = "{{down}}" >goDown</button>
<button bindtap= "goback" wx: else >goBack</button>
|
wxss1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | .box{
position: relative;
height: 200rpx;
overflow: hidden;
text-align: center;
color: white;
font-size: 120rpx;
}
.anl{
height: 200rpx;
background-color: red;
}
.anr{
background-color: green;
height: 400rpx;
width: 100%;
position: absolute;
left: 100%;
top: 0;
}
.add{
background-color: yellow;
height: 100rpx;
}
|
js1 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 40 41 42 43 44 45 46 47 48 49 50 | Page({
data: {
box: {},
anr: {},
down: true
},
add: function () {
this .setData({
down: false
});
var that = this ;
let option = {
duration: 1000,
timingFunction: 'ease-in'
};
var anr = wx.createAnimation(option);
this .anr=anr;
anr.left(0).step();
that.setData({
anr: anr.export()
});
var obj = wx.createSelectorQuery();
obj. select ( '.anr' ).boundingClientRect(function (rect) {
var box = wx.createAnimation(option);
that.box=box;
box.height(rect.height).step();
that.setData({
box: box.export()
});
}).exec();
},
goback:function(){
this .setData({
down: true
});
this .box.height( '200rpx' ).step();
this .setData({
box: this .box.export()
});
this .anr.left( '750rpx' ).step();
this .setData({
anr: this .anr.export()
})
}
})
|
|