无缝轮播图

本文最后更新于:2021年3月3日 凌晨

轮播图原理如下:

第四第五步正常来说是不能有延迟的,因为是同一张图
代码如下:

HTML

<div id="out">
	<div id="imgbox">
		<img src="./4.jpg" />
		<img src="./1.jpg" />
		<img src="./2.jpg" />
		<img src="./3.jpg" />
		<img src="./4.jpg" />
		<img src="./1.jpg" />
	</div>
</div>

Css

#out {
	position: relative;
	width: 100px;
	height: 100px;
	border: 5px solid lightcoral;
	overflow: hidden;
	margin: auto;
}

#imgbox {
	position: absolute;
	left: -100px;
	width: 600px;
	background-color: lightblue;
	display: flex;
	flex-direction: row;
}

#imgbox img {
	width: 100px;
	height: 100px;
	display: block;
}

Javascript

let box = document.getElementById("imgbox")
let temp = 0
function lunbo() {
	if (temp == -500) {
		temp = -100
		box.style.transition = "none"
		box.style.left = "-100px"
		setTimeout(function(){ //这里使用setTimeout是为了执行下面的函数,否则第四第五步会有延迟
			temp -= 100
			box.style.left = temp + "px"
			box.style.transition = "all .5s"
			},0)
		} else {
			temp -= 100
			box.style.left = temp + "px"
			box.style.transition = "all .5s"
		}
	}
let act = setInterval(lunbo, 1000)

2021/3/3新增

最近发现一个更加人性话的方法来消除延迟,通过监听图组的transitionend实现(没错,就是动画事件,阅读红宝石后学到的/(ㄒoㄒ)/~~),这次通过Vue实现

<template>
	<div id="imgGroup" ref="imgGroup">
		<div class="imgOut"><img src="../static/sights/4.png" /></div>
		<div class="imgOut"><img src="../static/sights/1.png" /></div>
		<div class="imgOut"><img src="../static/sights/2.png" /></div>
		<div class="imgOut"><img src="../static/sights/3.png" /></div>
		<div class="imgOut"><img src="../static/sights/4.png" /></div>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				page: 1,
				type: ''
			}
		},
		mounted() {
			this.type = this.getQueryString('type')
			this.$refs.imgGroup.style.top = "-560px"
			let imgMove = setInterval(this.nextImg, 3000)
			imgMove
			this.$refs.imgGroup.addEventListener("transitionend", () => {
				if (this.page == 4) {
					this.backImg()
				}
			})
			this.$refs.imgGroup.onmouseover = () => {
				clearInterval(imgMove)
			}
			this.$refs.imgGroup.onmouseout = () => {
				imgMove = setInterval(this.nextImg, 3000)
			}
		},
		methods: {
			nextImg() {
				this.$refs.imgGroup.style.transition = "all .5s"
				let temp = parseInt(this.$refs.imgGroup.style.top)
				this.$refs.imgGroup.style.top = temp - 560 + "px"
				this.page++
			},
			backImg() {
				this.$refs.imgGroup.style.transition = "none"
				this.$refs.imgGroup.style.top = 0 + "px"
				this.page = 0
			},
			change(e) {
				this.type = e
			}
		}
	}
</script>

<style>
	自行脑补充,嘻嘻(●'◡'●),(其实就是懒,不想把代码抽出来)
</style>

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!