html
<!-- 轮播图 -->
<div class="w-full" x-data="indexCarousel()" x-init="init()">
<div class="relative overflow-x-hidden" style="padding-top: 24%" x-spread="container">
<div class="absolute inset-0 flex" x-spread="imagesContainer" :class="!(last >= images.length || last < 0) && 'transition-transform'">
<template x-for="image in [images[images.length -1], ...images, images[0]]", :key="image">
<img :src="image" class="flex-shrink-0 w-full h-full object-center object-cover" style="-webkit-user-drag:none;pointer-events:none" />
</template>
</div>
<div class="absolute bottom-2 left-1/2 flex p-2 bg-white hover:shadow rounded-lg bg-opacity-0 hover:bg-opacity-90 transition">
<template x-for="(image, index) in images", :key="index">
<span class="w-3 h-3 inline-block rounded-full bg-gray-600 mx-1 cursor-pointer transition" :class="{'bg-red-600 w-5':(current===index)}" @click="update(index)"></span>
</template>
</div>
</div>
</div>
js
<script>
/**
* 首页轮播
* */
function indexCarousel(){
return {
images: ['/static/images/banner.webp', '/static/images/banner1.webp', '/static/images/banner2.webp'],
current: 0,
auto: true,
last: null,
autoT: null,
update(val) {
this.last = this.current; this.current = val;
},
startAuto() {
this.autoT = setTimeout(()=>{
this.startAuto()
if(this.auto) this.update(this.current + 1)
}, 5000)
},
init() {
this.$watch('current', (val) => {
if(val < -1) this.update(this.images.length + val); else if(val > this.images.length) this.update(val - this.images.length);
})
this.$watch('auto', () => { clearTimeout(this.autoT);this.startAuto() })
this.startAuto()
},
imagesContainer: {
[':style']: "`transform: translateX(${(current + 1) * -100}%)`",
['@transitionend']() { if (this.current === -1) update(this.images.length - 1); else if (this.current === this.images.length) this.update(0) }
},
container: {
['@mouseenter']() {
this.auto = false
},
['@mouseleave']() {
this.auto = true
},
['@mousedown']() {
console.log(1)
},
['@touchstart']() {
console.log(2)
},
}
}
}
</script>
在container里添加事件可实现滑动