欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JQuery实现轮播图

程序员文章站 2022-04-24 15:07:33
...

JQuery实现轮播图

 JQuery实现轮播图

JQuery实现轮播图

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<link rel="stylesheet" href="css/new_file.css" />
		<script type="text/javascript" src="js/jquery-3.3.1.js" ></script>
		<script type="text/javascript" src="js/new_file.js" ></script>
	</head>
	<body>
		<div class="scroll">
			<div class="box">
				<img class="scrollImg" src="img/pic-one.png" alt="">
				<img class="scrollImg" src="img/pic-two.png" alt="">
				<img class="scrollImg" src="img/pic-three.png" alt="">
				<img class="scrollImg" src="img/pic-fou.png" alt="">
			</div>
			<ul class="tabs">
				<li class="active">1</li>
				<li>2</li>
				<li>3</li>
				<li>4</li>
			</ul>
			<a class="btn btna" href="#"><</a>
			<a class="btn btnb"  href="#">></a>
		</div>
	</body>
</html>
body, ul, li, a{
	padding: 0px;
	margin: 0px;
	text-decoration: none;
	list-style: none;
}
.scroll{
	position: relative;
	width: 530px;
	height: 395px;
	border: 6px solid rgba(0, 0, 0, 0.5);
	margin: 50px auto;
	overflow: hidden;
}
.scrollImg{
	position: absolute;
}

.box img{
	float: left;
}
.tabs{
	position: absolute;
	bottom: 20px;
	left: 50%;
	transform: translateX(-50%);
}
.tabs li{
	display: inline-block;
	width: 20px;
	height: 20px;
	border-radius: 50%;
	background: #ccc;
	cursor: pointer;
	line-height: 20px;
	text-align: center;
}
.tabs .active{
	background: olivedrab;
}
.btn{
	width: 30px;
	height: 30px;
	background: rgba(44, 55, 66, 0.5);
	color: #fff;
	position: absolute;
	top: 50%;
	margin-top: -15px;
	font-size: 20px;
	text-align: center;
	line-height: 30px;
}
.btnb{
	right: 0px;
}
var i = 0;
var timer;
$(function() {
	$(".scrollImg").eq(0).show().siblings().hide();//第一张图片显示,其余兄弟图片隐藏
	showTime();
	//鼠标点击下发生变化
	$('li').hover(function() {
		i = $(this).index();
		show();
		clearInterval(timer);//清除轮播
	}, function() {
		showTime();
	});
	//给两个按钮绑定事件
	$(".btna").click(function() {
		clearInterval(timer);
		if(i == 0) {
			i = 4
		}
		i--;
		show();
		showTime();
	});
	$(".btnb").click(function() {
		clearInterval(timer);
		if(i == 3) {
			i = -1
		}
		i++;
		show();
		showTime();
	});
});

function show() {
	$('.scrollImg').eq(i).fadeIn(300).siblings().fadeOut();//第i张图片显示,其余图片隐藏
	$("li").eq(i).addClass("active").siblings().removeClass("active");//底部小标随图片轮播变换顺序
}

function showTime() {
	timer = setInterval(function() {  //间隔3秒,图片实现自动轮播
		i++;
		if(i == 4) {
			i = 0;
		}
		show();
	}, 3000);
}

JQuery实现轮播图