js和css实现简单的轮播图效果

我之前见网上的轮播图太复杂了,所以我来写一个简单的轮播图,本篇文章向大家介绍分别用js和css实现轮播图!

  • js实现轮播图

代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			body{
				background-color: #F5F5F5;
			}
			.wrapper {
				width: 1920px;
				height: 500px;
				margin: 0 auto;
				overflow: hidden;
			}

			.active {
				width: 7680px;
				height: 100%;
				white-space: nowrap;
				font-size: 0;
			}

		</style>
	</head>
	<body>
		<!-- 显示1张 ,改变wrapper的scrollLeft-->
		<div class="wrapper">
			<!-- 显示4张 -->
			<div class="active">
				<img src="../imgs/10079.jpg" >
				<img src="../imgs/10080.jpg" >
				<img src="../imgs/10081.jpg" >
				<img src="../imgs/10079.jpg" >
			</div>
		</div>
		<script type="text/javascript">
			var _wrapper = document.querySelector(".wrapper");
			var _imgs = document.querySelectorAll("img");
			var index = 0; //记录当前轮播的张数
			setInterval(function() {
				var speed = 40; //每30毫秒移动的距离
				var moveLength = 0; //一张图片的滚动距离
				var id = setInterval(function() {
					_wrapper.scrollLeft += speed;
					moveLength += speed;
					if (moveLength == 1920) {
						clearInterval(id);
					}
				}, 30) //1440毫秒
				index++;
				if (index == _imgs.length) {
					index = 0; //回到第一张
					_wrapper.scrollLeft = 0; //滚动回到原点
				}
			}, 3000)
		</script>
	</body>
</html>

运行效果:


  • css实现轮播图

代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
		body{
			background-color: #F5F5F5;
		}
			.wrapper{
				width:1920px;
				height: 500px;
				margin: 0 auto;
				overflow: hidden;
				position: relative;
			}
			.box{
				width: 7680px;
				height: 500px;
				position: absolute;
				animation: name 10s  infinite;
			}
			.box img{
				float: left;
			}
			
			@keyframes name{
				0%{
					left: 0;
				}
				15%{
					left: 0;
				}
				30%{
					left: -1920px;
				}
				45%{
					left: -1920px;
				}
				65%{
					left: -3840px;
				}
				80%{
					left: -3840px;
				}
				
				100%{
					left:-5760px;
				}
			}
		</style>
	</head>
	<body>
		<div class="wrapper">
			<div class="box">
				<img src="img/10079.jpg" >
				<img src="img/10080.jpg" >
				<img src="img/10081.jpg" >
				<img src="img/10079.jpg" >
			</div>
		</div>
	</body>
</html>

运行效果:

有疑问欢迎评论区留言、私信!

猜你喜欢

转载自blog.csdn.net/qq_46362763/article/details/123582821