今天在测试微信小程序动画的时候遇到了坑,需求是这样的点击时子元素从外部滑动回来,父元素的高度跟随子元素的高度改变。
实现子元素left为0并不复杂,但是改变父元素box的高度的时候却遇到了坑,因为是需要跟随子元素right的高度来改变父元素box的高度的,并且子元素right的高度不确定,我们需要先获取子元素的高度。
在改变高度的时候出错了,高度未改变。在测试时发现
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,原来是一个异步操作,这就可以理解为什么执行无效了。改成这样
obj.select('.anr').boundingClientRect(function (rect) {//获取子元素高度
var box = wx.createAnimation(option); // 创建动画
box.height(rect.height).step();//改变父元素高度
that.setData({
box: box.export()
});
}).exec();
想着应该没问题了,但是遇到了另外一个坑,父元素的高度一下子变成了预设的效果,并没有Animation的渐变效果。本身父元素的高度是由left这个子元素撑起来的,给父元素预设一个高度这个问题就解决了。渐变效果就实现了。
源码解析
wxml
<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>
wxss
/* pages/userinfo/index.wxss */
.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;
}
js
// pages/userinfo/index.js
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()
})
}
})