使用元素JS制作简单的轮播特效,定时器设置自动轮播

使用原生JavaScript制作一个简答的图片轮播效果,没有实现动画。原理很简单,只需要使用DOM对象操作节点的添加和删除即可实现轮播功能,看一下效果图:

下面开始上代码:
HTML代码

<!-- .swiper是轮播的外部容器
			 .swiper-item是轮播的每个元素,在该标签中放置图片
		 -->
<div id="swiper">
	<div class="swiper-item">
		<img src="img/01.jpg">
	</div>
	<div class="swiper-item">
		<img src="img/02.jpg">
	</div>
	<div class="swiper-item">
		<img src="img/03.jpg">
	</div>
	<div class="swiper-item">
		<img src="img/04.jpg">
	</div>
</div>

<!-- 分页指示器 -->
<div id="point">
	<div class="point-item point-active"></div>
	<div class="point-item"></div>
	<div class="point-item"></div>
	<div class="point-item"></div>
</div>

<!-- 控制轮播的按钮 -->
<div style="text-align: center;">
	<button id="up">上一张</button>
	<button id="down">下一张</button>
</div>

CSS代码:

/* 轮播外部容器样式 */
#swiper {
	margin: 10px auto;
	width: 360px;
	height: 200px;
	border: 1px solid #999;
	overflow: hidden; /* 注释本行代码,查看图片的轮播效果 */
}

/* 设置轮播图片样式 */
.swiper-item img {
	width: 100%;
}

/* 分页指示器样式 */
#point {
	width: 80px;
	height: 15px;
	margin: 10px auto;
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-around;
}

.point-item {
	border: 1px solid #999;
	width: 10px;
	height: 10px;
	border-radius: 50%;
}

/* 指示器激活样式 */
.point-active {
	background-color: red;
}

JavaScript代码:

//获取轮播容器对象 和 分页指示器元素对象
var swiper = document.getElementById('swiper');
var point = document.getElementById('point');


//播放下一张图片的方法
function changeAfter() {
	//1. 删除轮播容器中第一个子元素,并返回被删除的元素对象
	//swiper.children 返回swiper元素下的所有子元素
	var child = swiper.removeChild(swiper.children[0]);
	//2. 将被删除元素追加到轮播容器的末尾
	swiper.appendChild(child);

	//设置分页指示器的轮播效果,要与图片轮播顺序相反
	var index = point.children.length - 1;
	var pointItem = point.removeChild(point.children[index]);
	point.insertBefore(pointItem, point.children[0]);

}

//播放上一张图片的方法
function changeBefore() {
	//1. 获取最后一张在轮播容器中的的下标
	var index = swiper.children.length - 1;
	//2. 把最后一张删除,并返回被删除的元素对象
	var child = swiper.removeChild(swiper.children[index]);
	//3. 将被删除元素添加到第一张之前
	swiper.insertBefore(child, swiper.children[0]);

	//设置分页指示器的轮播效果,要与图片轮播顺序相反
	var pointItem = point.removeChild(point.children[0]);
	point.appendChild(pointItem);
}

//上一张按钮点击事件
document.getElementById("up").onclick = function() {
	changeBefore(); //调用轮播上一张的方法
}
//下一张按钮点击事件
document.getElementById("down").onclick = function() {
	changeAfter(); //调用轮播下一张的方法
}

//定时轮播
setInterval('changeAfter()', 3000);

posted @ 2020-05-11 22:04  Web1024  阅读(1191)  评论(0编辑  收藏  举报