这是马。
style
<style>
#app {
width: 400px;
}
.horse {
height: 80px;
}
.box {
list-style: none;
}
.horse {
position: relative;
left: 0;
}
img {
height: 80px;
width: 100px;
}
.endLine {
position: absolute;
display: flex;
height: 400px;
width: 40px;
left: 500px;
transform: rotate(180deg);
}
</style>
HTML
一个开始,一个暂停,循环一下马的数组,通过修改left,让马跑起来。
<div id="app">
<button @click="start" style="width:80px">开始</button>
<button @click="pause" style="width:80px">暂停</button>
<ul class="box">
<li v-for="(item,index) in arr" class="horse" :style="{left:item.value+'px'}">
<img src="../lib/horse.gif" alt="">
</li>
</ul>
</div>
JS
搞几个定时器,跑一跑,然后通过Promise.race(),知道最先跑完的马,然后取消定时器,第一的就获胜了。
new Vue({
el: '#app',
data() {
return {
isOver: false,
tiemList: [],
arr: [{ key: 'a', value: 0, speed: 5 }, { key: 'b', value: 0, speed: 2 }, { key: 'c', value: 0, speed: 4 },
{ key: 'd', value: 0, speed: 3 }, { key: 'e', value: 0, speed: 1 }]
}
},
methods: {
pause() {
this.tiemList.forEach(item => {
clearInterval(item)
})
},
start() {
let promise = this.arr.map((item, index) => {
return new Promise((resolve, reject) => {
let inter = setInterval(() => {
item.value = item.value + item.speed
if (item.value >= 400) {
clearInterval(inter)
resolve(index)
}
}, 100)
this.tiemList.push(inter)
})
})
Promise.race(promise).then(res => {
this.tiemList.forEach(item => {
clearInterval(item)
})
this.$confirm(`${res + 1}号,获胜了`, '提示', {
confirmButtonText: '确定',
type: 'success'
}).then(() => {
})
})
}
}
})