HTML+CSS +JS实现轮播图的四种方法

HTML+CSS +JS实现轮播图

轮播图能够自动播放,当点击左右箭头时可以手动切换图片;当鼠标移入圆点时,自动播放停止,显示当前图片;当鼠标移出圆点时,图片又从当前图片开始自动播放;当鼠标点击圆点时,可以手动切换图片;图片的播放是循环的。

一、使用全局变量实现轮播图

1、布局——HTML + CSS

首先,在页面放一个整体的大盒子,在大盒子中装几个小盒子,分别用于放图片、左右点击箭头、底部切换的圆点。

<div id="box">
    <!-- 放图片-->
	<div id="lunboimg">
		<a href="#">
		<!-- 仅放一张图片,通过JS来改变图片地址即可,也可以放多个a标签,在每个a标签中放图片-->
		      <img src="img/0.jpg" />
		</a>
	</div>
	<!-- 放底部圆点-->
	<div id="selector">
		<span id=""></span>
		<span id=""></span>
		<span id=""></span>
		<span id=""></span>
	</div>
	<!-- 左箭头-->
	<div id="left">&lt;</div>
	<!-- 右箭头-->
	<div id="right">&gt;</div>

对添加的盒子设置合适的样式即可

2、实现步骤——JS

(1)布局
(2)通过document去获取页面元素。圆点获取后返回数组,用于图片切换时便于得到当前图片地址;获取的img元素,可以通过img.src去改变图片的地址,从而实现页面放置一个img可以实现轮播图。

//获取图片
let img = document.querySelector('img');
//获取圆点
let span = document.querySelectorAll('span');
//获取左边箭头
let left = document.getElementById('left');
//获取右边箭头
let right = document.getElementById('right');
//初始化当前图片下标
let index = 0;
//timer用于获取自动播放轮播图是设置的定时器的返回值
let timer;

(3)设置定时器让轮播图自动播放

//设置定时器并接收返回值,便于停止自动播放
timer = setInterval(function() {
	if (index == span.length) {
	index = 0;
	}
	show();
    index++;
}, 1000);

(4)设置圆点手动控制切换图片

for(let i = 0; i < span.length; i++){
		//为每个小圆点设置点击事件
		span[i].onclick = function(){
		    index = i;
			show();
		}
}

(5)设置左右箭头手动切换图片

//为左边箭头设置点击事件
left.onclick = function(){
	//实现循环
	if(index <= 0){
	    index = span.length - 1;
	}else{
		index --;
	}
	show();
}
//为右边箭头设置点击时间
right.onclick = function(){
    //当index累加到圆点的数量时,将index置为0,从头开始,实现循环
	if(index == span.length){
		index = 0;
	}
	index ++;
	show();
}

(6)对小圆点设置鼠标移入移出监听

//为每个小圆点都设置事件监听
for(let i = 0; i < span.length; i++){
    //设置鼠标移入监听
	span[i].addEventListener('mouseenter',function(){
			//清除自动播放效果
			clearInterval(timer);
			index = i;
			//显示当前图片
			show();
	},false);
	//设置鼠标移出监听
	span[i].addEventListener('mousemove',function(){
			//清除自动播放效果
			clearInterval(timer);
			//设置鼠标移出后从当前位置开始自动播放
			autoPlay();
	},false);
					
}
3、代码详解
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>轮播图</title>
		<style type="text/css">
			* {
				box-sizing: border-box;
				margin: 0;
				padding: 0;
			}

			#box {
				width: 200px;
				height: 200px;
				overflow: hidden;
				position: relative;
			}

			#lunboimg {
				width: 200px;
				height: 200px;
				position: absolute;
				display: flex;
			}

			a {
				height: 200px;
				width: 200px;
			}

			img {
				width: 200px;
				height: 200px;
				margin: 0;
			}

			#box:hover #selector {
				display: flex;
			}

			#selector {
				width: 80px;
				height: 20px;
				position: absolute;
				bottom: 0;
				left: 60px;
				display: none;
				justify-content: space-between;
				z-index: 100;
			}

			#selector>span {
				width: 15px;
				height: 15px;
				border-radius: 50%;
				background-color: lightsalmon;
				opacity: 0.8;
				margin-right: 5px;
				cursor: pointer;
			}

			#selector>span:hover {
				background-color: #8A8A8A;
			}
			#left,#right{
				width: 20px;
				height: 20px;
				position: absolute;
				top: 90px;
				background-color: lightsteelblue;
				font-size: 18px;
				border-radius: 50%;
				text-align: center;
				line-height: 100%;
				cursor: pointer;
				color: lightslategray;
			}
			#left{
				left: 0;
			}
			#right{
				right: 0;
			}
			#left:hover,#right:hover{
				background-color: #8A8A8A;
				color: #FFFFFF;
			}
		</style>
	</head>
	<body>
		<div id="box">
			<!-- 放图片-->
			<div id="lunboimg">
				<a href="#">
					<!-- 仅放一张图片,通过JS来改变图片地址即可-->
					<img src="img/0.jpg" />
				</a>
			</div>
			<!-- 放底部圆点-->
			<div id="selector">
				<span id=""></span>
				<span id=""></span>
				<span id=""></span>
				<span id=""></span>
			</div>
			<!-- 左箭头-->
			<div id="left">&lt;</div>
			<!-- 右箭头-->
			<div id="right">&gt;</div>
		</div>

		<script type="text/javascript">
			let img = document.querySelector('img');
			let span = document.querySelectorAll('span');
			let left = document.getElementById('left');
			let right = document.getElementById('right');
			let index = 0;
			let timer;
			function show(){
				img.src = `img/${index}.jpg`;
			}

			function autoPlay() {
				timer = setInterval(function() {
					if (index == span.length) {
						index = 0;
					}
					show();
					index++;
				}, 1000);
			}
			autoPlay();
			
			function ctrlPlay(){
				for(let i = 0; i < span.length; i++){
					span[i].onclick = function(){
						index = i;
						show();
					}
				}
			}
			ctrlPlay();
			function clickPlay(){
				left.onclick = function(){
					if(index <= 0){
						index = span.length - 1;
					}else{
						index --;
					}
					show();
				}
				right.onclick = function(){
					if(index == span.length){
						index = 0;
					}
					index ++;
					show();
				}
			}
			clickPlay();
			function eventList(){
				for(let i = 0; i < span.length; i++){
					span[i].addEventListener('mouseenter',function(){
						clearInterval(timer);
						index = i;
						show();
					},false);
					span[i].addEventListener('mousemove',function(){
						clearInterval(timer);
						autoPlay();
					},false);
					
				}
			}
			eventList();
		</script>
	</body>
</html>

二、使用构造函数实现轮播图

1、布局——HTML + CSS

首先,在页面放一个整体的大盒子,在大盒子中装几个小盒子,分别用于放图片、左右点击箭头、底部切换的圆点。

<div id="box">
    <!-- 放图片-->
	<div id="lunboimg">
		<a href="#">
		<!-- 仅放一张图片,通过JS来改变图片地址即可,也可以放多个a标签,在每个a标签中放图片-->
		      <img src="img/0.jpg" />
		</a>
	</div>
	<!-- 放底部圆点-->
	<div id="selector">
		<span id=""></span>
		<span id=""></span>
		<span id=""></span>
		<span id=""></span>
	</div>
	<!-- 左箭头-->
	<div id="left">&lt;</div>
	<!-- 右箭头-->
	<div id="right">&gt;</div>

对添加的盒子设置合适的样式即可

2、实现步骤——JS

(1)布局
(2)写一个构造函数,在构造函数中通过this添加属性:

//获取页面img元素
this.img = document.querySelector('img');
//获取底部点击小圆点
this.span = document.querySelectorAll('span');
//获取左箭头
this.left = document.getElementById('left');
//获取右箭头
this.right = document.getElementById('right');
//初始化小圆点下标
this.index = 0;
//初始化timer,用于接收定时器的返回值,便于停止定时器和打开定时器
this.timer = null;

(3)设置定时器让轮播图自动播放,并将值返回给timer,在给定时器传参时要改变参数函数的this的指向,让this指向构造函数;定时器应该放在构造函数的原型之上的一个方法中,并对该函数改变this指向,让this指向构造函数。

//在原型上创建方法用于然那个轮播图自动播放
PlayImg.prototype.autoPlay = function() {
	//查看当前的this
	console.log(this);
	//设置定时器并将返回值赋给timer保存
	this.timer = setInterval(function() {
	    //让图片循环播放
	    if (this.index == this.span.length) {
			this.index = 0;
	    }
	    //显示图片
	    this.show();
	    //让图片动起来
	    this.index++;
	}.bind(this), 1000);//改变this指向
}.bind(this);//改变this指向

(4)在构造函数的原型上添加方法用于点击圆点切换图片,通过for循环对每一个小圆点设置点击事件,并对点击事件改变this指向,然那个this总是指向构造函数;再对整个方法改变this指向,让this指向构造函数。

//再原型上添加方法用于点击圆点七日换图片
PlayImg.prototype.pointCtrlPlay = function() {
	//查看当前this
	console.log(this);
	//通过for循环为小圆点一次添加点击事件
	for (let i = 0; i < this.span.length; i++) {
		this.span[i].onclick = function() {
			this.index = i;
			this.show();
		}.bind(this);//改变this指向
	}
}.bind(this);//改变this指向

(5)在构造函数原型上添加方法用于点击左右箭头切换图片。分别对左右箭头设置点击事件,并改变事件的this指向,再对整个方法改变this指向。

//在构造函数原型上添加方法用于点击左右箭头切换图片
PlayImg.prototype.ctrlPlay = function() {
	//查看当前this
	console.log(this);
	//设置左箭头点击事件
	this.left.onclick = function() {
		if (this.index <= 0) {
			this.index = this.span.length - 1;
		} else {
			this.index--;
		}
		this.show();
	}.bind(this);//改变this指向
	//设置右箭头点击事件
	this.right.onclick = function() {
		if (this.index == this.span.length) {
			this.index = 0;
		}
		this.index++;
		this.show();
	}.bind(this);//改变this指向
}.bind(this);//改变this指向

(6)为小圆点设置鼠标移入移出事件监听,当鼠标移入某个小圆点时,图片停止自动播放并显示当前图片,当鼠标移出小圆点时,图片从当前开始自动播放。在构造函数上添加方法用于设置监听函数,通过for循环对每个小圆点设置监听,并对监听函数改变this指向,让this一直指向构造函数。

//在原型上添加方法用于监听鼠标移入移出
PlayImg.prototype.eventListener = function() {
	//查看当前this指向
	console.log(this);
	for (let i = 0; i < this.span.length; i++) {
	    //设置鼠标移入监听'mouseenter'
	    this.span[i].addEventListener('mouseenter', function() {
		    //清除定时器
		    clearInterval(this.timer);
			this.index = i;
			this.show();
			//设置false,让监听在页面加载时开始监听
		}.bind(this), false);//改变this指向
		//添加鼠标移出监听'mousemove'
		this.span[i].addEventListener('mousemove', function() {
			//清除定时器
			clearInterval(this.timer);
			this.show();
			//重新打开一个定时器
			this.autoPlay();
		}.bind(this), false);//改变this指向
	}
}.bind(this);//改变this指向

(7)根据构造函数,new一个对象,通过对象去访问构造函数原型上的方法

let play = lunboImg();
//new 一个对象
let r = new play();
//自动播放
r.autoPlay();
//左右箭头切换
r.ctrlPlay();
//小圆点点击切换
r.pointCtrlPlay();
//小圆点鼠标移入移出
r.eventListener();

3、整体效果的代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			* {
				box-sizing: border-box;
				margin: 0;
				padding: 0;
			}

			#box {
				width: 200px;
				height: 200px;
				overflow: hidden;
				position: relative;
			}

			#lunboimg {
				width: 200px;
				height: 200px;
				position: absolute;
				display: flex;
			}

			a {
				height: 200px;
				width: 200px;
			}

			img {
				width: 200px;
				height: 200px;
				margin: 0;
			}

			#box:hover #selector {
				display: flex;
			}

			#selector {
				width: 80px;
				height: 20px;
				position: absolute;
				bottom: 0;
				left: 60px;
				display: none;
				justify-content: space-between;
				z-index: 100;
			}

			#selector>span {
				width: 15px;
				height: 15px;
				border-radius: 50%;
				background-color: lightsalmon;
				opacity: 0.8;
				margin-right: 5px;
				cursor: pointer;
			}

			#selector>span:hover {
				background-color: #8A8A8A;
			}

			#left,
			#right {
				width: 20px;
				height: 20px;
				position: absolute;
				top: 90px;
				background-color: lightsteelblue;
				font-size: 18px;
				border-radius: 50%;
				text-align: center;
				line-height: 100%;
				cursor: pointer;
				color: lightslategray;
			}

			#left {
				left: 0;
			}

			#right {
				right: 0;
			}

			#left:hover,
			#right:hover {
				background-color: #8A8A8A;
				color: #FFFFFF;
			}
		</style>
	</head>
	<body>
		<div id="box">
			<div id="lunboimg">
				<a href="#">
					<img src="img/0.jpg" />
				</a>
			</div>
			<div id="selector">
				<span id=""></span>
				<span id=""></span>
				<span id=""></span>
				<span id=""></span>
			</div>
			<div id="left">&lt;</div>
			<div id="right">&gt;</div>
		</div>
		<script type="text/javascript">
			function lunboImg() {
				function PlayImg() {
					this.img = document.querySelector('img');
					this.span = document.querySelectorAll('span');
					this.left = document.getElementById('left');
					this.right = document.getElementById('right');
					this.index = 0;
					this.timer = null;
					this.show = function() {
						this.img.src = `img/${this.index}.jpg`;
					}.bind(this);
					PlayImg.prototype.autoPlay = function() {
						console.log(this);
						this.timer = setInterval(function() {
							if (this.index == this.span.length) {
								this.index = 0;
							}
							this.show();
							this.index++;
						}.bind(this), 1000);
					}.bind(this);
					PlayImg.prototype.pointCtrlPlay = function() {
						console.log(this);
						for (let i = 0; i < this.span.length; i++) {
							this.span[i].onclick = function() {
								this.index = i;
								this.show();
							}.bind(this);
						}
					}.bind(this);
					PlayImg.prototype.ctrlPlay = function() {
						console.log(this);
						this.left.onclick = function() {
							if (this.index <= 0) {
								this.index = this.span.length - 1;
							} else {
								this.index--;
							}
							this.show();
						}.bind(this);
						this.right.onclick = function() {
							if (this.index == this.span.length) {
								this.index = 0;
							}
							this.index++;
							this.show();
						}.bind(this);
					}.bind(this);
					PlayImg.prototype.eventListener = function() {
						console.log(this);
						for (let i = 0; i < this.span.length; i++) {
							this.span[i].addEventListener('mouseenter', function() {
								clearInterval(this.timer);
								this.index = i;
								this.show();
							}.bind(this), false);
							this.span[i].addEventListener('mousemove', function() {
								clearInterval(this.timer);
								this.show();
								this.autoPlay();
							}.bind(this), false);
						}
					}.bind(this);
				}
				return PlayImg;
			}
			let play = lunboImg();
			let r = new play();
			r.autoPlay();
			r.ctrlPlay();
			r.pointCtrlPlay();
			r.eventListener();
		</script>
	</body>
</html>

或者不使用bind()来改变this指向,而通过箭头函数去实现:

function lunboImg() {
	function PlayImg() {
		this.img = document.querySelector('img');
		this.span = document.querySelectorAll('span');
		this.left = document.getElementById('left');
		this.right = document.getElementById('right');
		this.index = 0;
		this.timer = null;
		this.show = () => {
			this.img.src = `img/${this.index}.jpg`;
		}
		PlayImg.prototype.autoPlay = () => {
			console.log(this);
			this.timer = setInterval(() => {
				if (this.index == this.span.length) {
					this.index = 0;
				}
				this.show();
				this.index++;
			}, 1000);
		}
		PlayImg.prototype.pointCtrlPlay = () => {
			console.log(this);
			for (let i = 0; i < this.span.length; i++) {
				this.span[i].onclick = () => {
					this.index = i;
					this.show();
				}
			}
		}
		PlayImg.prototype.ctrlPlay = () => {
			console.log(this);
			this.left.onclick = () => {
				if (this.index <= 0) {
					this.index = this.span.length - 1;
				} else {
					this.index--;
				}
				this.show();
			};
			this.right.onclick = () => {
				if (this.index == this.span.length) {
				    this.index = 0;
				}
				this.index++;
				this.show();
			};
	}
	PlayImg.prototype.eventListener = () => {
		console.log(this);
		for (let i = 0; i < this.span.length; i++) {
			this.span[i].addEventListener('mouseenter', () => {
				clearInterval(this.timer);
				this.index = i;
				this.show();
			}, false);
			this.span[i].addEventListener('mousemove', () => {
				clearInterval(this.timer);
				this.show();
				this.autoPlay();
		    }, false);
		  }
	  }
   }
	return PlayImg;
}

三、js类+模块方法实现轮播图

步骤同上,具体的js代码如下:

classLB.js文件

class ClassLB {
	constructor() {
		this.img = document.querySelectorAll('.img img');
		this.point = document.querySelectorAll('.point li');
		this.index = 0;
		this.timer = null;
	}
	show() {
		for (let i = 0; i < this.img.length; i++) {
			this.img[i].style.display = 'none';
			this.point[i].style.backgroundColor = '#fff';
		}
		this.img[this.index % this.img.length].style.display = 'block';
		this.point[this.index % this.point.length].style.backgroundColor = '#f00';
	}
	autoPlay() {
		this.timer = setInterval(() => {
			this.index++;
			this.show();
		}, 1000);
	}

	pointCtrl() {
		for (let i = 0; i < this.length; i++) {
			this.point[i].onclick = function() {
				this.index = i;
				this.show();
			}
		}
	}

	lrCtrl() {
		document.querySelector(".left").onclick = () => {
			if (this.index <= 0) {
				this.index = this.img.length - 1
			} else {
				this.index--;
			}
			this.show();
		}

		document.querySelector(".right").onclick = () => {
			this.index++;

			this.show();
		}
	}
	addEvent() {
		for (let i = 0; i < this.point.length; i++) {
			this.point[i].addEventListener('mouseenter', () => {
				clearInterval(this.timer);
				this.index = i;
				this.show();
			}, false);
			this.point[i].addEventListener('mousemove', () => {
				clearInterval(this.timer);
				this.index = i;
				this.show();
				this.autoPlay();
			}, false);
		}
	}

}
export default ClassLB;

body中:

        <script type="module">
			import ClassLB from "./js/classLB.js";
			let classLB = new ClassLB();
			classLB.autoPlay();
			classLB.lrCtrl();
			classLB.pointCtrl();
			classLB.addEvent();
		</script>

四、仅使用css和html实现轮播图

  • 方法一:box-box-ul-li-a-img
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>轮播图</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        li{
            float: left;
            list-style: none;
        }
        .box{
            width: 700px;
            overflow: hidden;
            position: relative;
            height: 360px;
            margin-left: 300px;
        }
        .box img{
            width: 700px;
            height: 360px;
        }
        ul{
            width: 2100px;
            height: 360px;
            position: absolute;
            left: 0;
            top: 0;
            animation: myanimation 8s infinite;
        }
        @keyframes myanimation {
            0%,25%{
                left: 0;
            }
            35%,60%{
                left: -700px;
            }
            70%,90%{
                left: -1400px;
            }
        }

    </style>
</head>
<body>
    <div class="box">
        <ul>
            <li>
                <img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/35a2239e10e392af73b6b7a737a039d6.jpg?w=632&h=340" alt="">
            </li>
            <li>
                <img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/50beb6e77e316ff0637d79ad1869572e.jpg?w=632&h=340" alt="">
            </li>
            <li>
                <img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/816a66edef10673b4768128b41804cae.jpg?w=632&h=340" alt="">
            </li>
        </ul>
    </div>
</body>
</html>
  • 方法二:box-box-a-img
 <div class="content-middle">
            <div class="middle-box">
                <a href="">
                    <img src="http://static.basicedu.chaoxing.com/erya_new/upload/swiper16.jpg" alt="">
                </a>
                <a href="">
                    <img src="http://static.basicedu.chaoxing.com/erya_new/upload/swiper7.png" alt="">
                </a>
                <a href="">
                    <img src="http://static.basicedu.chaoxing.com/erya_new/upload/swiper2.png" alt="">
                </a>
                <a href="">
                    <img src="http://static.basicedu.chaoxing.com/erya_new/upload/swiper3.png" alt="">
                </a>
                <a href="">
                    <img src="http://static.basicedu.chaoxing.com/erya_new/upload/swiper4.png" alt="">
                </a>
                <a href="">
                    <img src="http://static.basicedu.chaoxing.com/erya_new/upload/swiper10.jpg" alt="">
                </a>
                <a href="">
                    <img src="http://static.basicedu.chaoxing.com/erya_new/upload/swiper11.jpg" alt="">
                </a>
                <a href="">
                    <img src="http://static.basicedu.chaoxing.com/erya_new/upload/swiper12.jpg" alt="">
                </a>
                <a href="">
                    <img src="http://static.basicedu.chaoxing.com/erya_new/upload/swiper13.jpg" alt="">
                </a>
                <a href="">
                    <img src="http://static.basicedu.chaoxing.com/erya_new/upload/swiper14.jpg" alt="">
                </a>
                <a href="">
                    <img src="http://static.basicedu.chaoxing.com/erya_new/upload/swiper15.jpg" alt="">
                </a>
            </div>
        </div>

css文件:

.content-middle{
    width: 100%;
    overflow: hidden;
    position: relative;
    height: 260px;
    
}
.middle-box a{
    display: inline-block;
    width: 315px;
    height: 260px;
}
.middle-box img{
    width: 315px;
    height: 260px;
}
.middle-box{
    width: 3715px;
    height: 260px;
    position: absolute;
    display: flex;
    justify-content: space-between;
    left: 0;
    top: 0;
    animation: myanimation2 20s infinite;
}

@keyframes myanimation2 {
    0%,5%{
        left: 0;
    }
    10%,15%{
        left: -340px;
    }
    20%,25%{
        left: -680px;
    }
    30%,35%{
        left: -1020px;
    }
    40%,45%{
        left: -1360px;
    }
    50%,55%{
        left: -1700px;
    }
    60%,65%{
        left: -2040px;
    }
    70%,75%{
        left: -2380px;
    }
    80%,85%{
        left: -2455px;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42602282/article/details/106842116