教你如何用VUE实现一个无缝横向滚动抽奖的效果
<template>
<div class="lottery-container">
<div class="lottery-button" @click="startLottery">点击抽奖</div>
<div class="prize-list" :style="{ '--index': currentIndex }" @transitionend="onTransitionEnd">
<div class="prize-item" v-for="(prize, index) in prizes" :key="index">
{{ prize.name }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
prizes: [
{ name: '奖品一' },
{ name: '奖品二' },
{ name: '奖品三' },
// ...更多奖品
],
isAnimating: false,
};
},
methods: {
startLottery() {
if (this.isAnimating) return;
const nextIndex = this.getRandomIndex();
this.animate(nextIndex);
},
animate(nextIndex) {
this.isAnimating = true;
this.currentIndex = nextIndex;
},
onTransitionEnd() {
this.isAnimating = false;
// 这里可以添加中奖后的处理逻辑,例如发放奖品
},
getRandomIndex() {
return Math.floor(Math.random() * this.prizes.length);
},
},
};
</script>
<style scoped>
.lottery-container {
position: relative;
width: 300px;
height: 150px;
overflow: hidden;
}
.lottery-button {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
width: 100px;
height: 30px;
line-height: 30px;
text-align: center;
background-color: #f00;
color: #fff;
cursor: pointer;
}
.prize-list {
display: flex;
width: 300%;
animation: slide 2s var(--ease-in-out) forwards;
transform: translateX(-calc(var(--index) * 100%));
}
.prize-item {
flex: 1 0 100%;
text-align: center;
line-height: 150px;
}
@keyframes slide {
to {
transform: translateX(-calc(var(--index) * 100%));
}
}
/* 自定义缓动函数 */
.lottery-container {
--ease-in-out: cubic-bezier(0.445, 0.05, 0.55, 0.95);
}
</style>
这个代码实例提供了一个基本的无缝横向滚动抽奖的Vue组件。用户点击"点击抽奖"按钮后,会随机滚动至一个奖品项。你可以在onTransitionEnd
方法中添加中奖后的处理逻辑,例如发放奖品。这个例子使用了CSS动画和Vue的数据绑定来实现动态的滚动效果。
评论已关闭