需求:
采用uni.createAnimation,为文件列表调换位置添加动画效果
效果图
代码
<view>
<view class="section-title">修改前</view>
<view class="file-section" :animation="animationData1">
业务内容代码。。。
</view>
<view class="section-title">修改后</view>
<view class="file-section" :animation="animationData2">
业务内容代码。。。
</view>
<button @click="swap">交换位置</button>
</view>
const animationData1 = ref(null);
const animationData2 = ref(null);
const isAnimating = ref(false);
const fileList = ref([]); //文件列表
// 创建动画实例
function createAnimation() {
const animation1 = uni.createAnimation({
duration: 300,
timingFunction: 'linear',
delay: 0
});
const animation2 = uni.createAnimation({
duration: 300,
timingFunction: 'linear',
delay: 0
});
return { animation1, animation2 };
}
function swap() {
isAnimating.value = true;
// 获取元素位置信息
const query = uni.createSelectorQuery();
query.selectAll('.file-section').boundingClientRect(data => {
if (!data || data.length < 2) {
isAnimating.value = false;
return;
}
const [section1Rect, section2Rect] = data;
const { animation1, animation2 } = createAnimation();
// 计算相对位移
const moveY1 = section2Rect.top - section1Rect.top;
const moveY2 = section1Rect.top - section2Rect.top;
// 应用动画
animation1.translateY(moveY1).step();
animation2.translateY(moveY2).step();
animationData1.value = animation1.export();
animationData2.value = animation2.export();
// 动画结束后交换数据
setTimeout(() => {
// 交换数据
fileList = fileList.reverse()
// 重置动画状态
animation1.translateY(0).step({ duration: 0 });
animation2.translateY(0).step({ duration: 0 });
animationData1.value = animation1.export();
animationData2.value = animation2.export();
isAnimating.value = false;
}, 1000);
}).exec();
}
onMounted(() => {
// 初始化动画数据
const { animation1, animation2 } = createAnimation();
animationData1.value = animation1.export();
animationData2.value = animation2.export();
});