当前位置: 首页 > 工具软件 > AutoAnimate > 使用案例 >

利用jQuery的animate实现轮播图

裴金鑫
2023-12-01
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
		//设置样式使图片在固定div中显示
			#d1{
				width: 1300px;
				height: 280px;
				display: flex;
			}
			#OWindow{
				width: 520px;
				height: 280px;
				margin: 0 auto;
				overflow: hidden;
				display: flex;
				position: relative;
			}
			#pictureDiv{
				left: -520px;
				display: flex;
				position: absolute;
			}
			#pictureDiv>div{
				width: 520px;
				height: 280px;
			}
			#num>div{
				width: 20px;
				height: 20px;
				border: 1px solid black;
			}
		</style>
	</head>
	<body>
		<div id="d1">
			<div id="OWindow">
				<div id="pictureDiv">
					<div style="background-image: url(img/04.jpg);">4</div>
					<div style="background-image: url(img/01.jpg);">1</div>
					<div style="background-image: url(img/02.jpg);">2</div>
					<div style="background-image: url(img/03.jpg);">3</div>
					<div style="background-image: url(img/04.jpg);">4</div>
					<div style="background-image: url(img/01.jpg);">1</div>
				</div>
			</div>
		</div>
		<div id="num" style="display: flex; margin-left: 822px;">
			<div style="background-color: pink;">1</div>
			<div>2</div>
			<div>3</div>
			<div>4</div>
		</div>
		<button id="btnPrev" style="margin-left: 400px;">上一个</button>
		<button id="btnNext" style="margin-left: 400px;">下一个</button>
	</body>
	<script type="text/javascript" src="js/jquery-3.6.0.min.js"></script>
	<script type="text/javascript">
		var count=2;
		//使图片完成轮播函数
		var method1000=function(){
			$("#pictureDiv").animate({"left":-520*count+"px"},1000);
			if(count==5){
				count=2;
				$("#pictureDiv").animate({"left":"-520px"},0)
			}
			else{
				count++;
			}
			changeColor();
		}
		//完成点击下一张和上一张的图片
		var method100=function(){
			$("#pictureDiv").animate({"left":-520*count+"px"},100);
			if(count==5){
				count=2;
				$("#pictureDiv").animate({"left":"-520px"},0)
			}
			else if(count==0){
				count=5;
				$("#pictureDiv").animate({"left":"-2080px"},0)
			}
			else{
				count++;
			}
			changeColor();
		}
		//实现轮播
		var inter=setInterval(method1000,3000);
		$("#btnNext").click(function(){
			clearInterval(inter);
			method100();
			inter=setInterval(method1000,3000);
			changeColor();
		})
		$("#btnPrev").click(function(){
			clearInterval(inter);
		    if(count<2){
				count=0;
			}
			else if(count==3){
				count=1;
			}
			else{
				count-=2;
			}
			method100();
			inter=setInterval(method1000,3000);
			changeColor();
		})
		$("#num>div").click(function(){
			clearInterval(inter);
			count=$(this).index()+1;
			method100();
			inter=setInterval(method1000,3000);
			changeColor();
		})
		function changeColor(){
			$("#num>div").css("background-color","white");
			$("#num>div").eq(count-2).css("background-color","pink");
		}
	</script>
</html>

 类似资料: