<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Banner</title>
	<style type="text/css">
	*{margin:0;padding: 0;}
	.container{width: 1079px;height: 500px;overflow: hidden;margin:0 auto;position: relative;}
	#list{width: 7553px;height: 500px;position: absolute;}
	#list img{width: 14.285715%;;float: left;}
	.arrow{position: absolute;color:#fff;text-decoration: none;bottom: 20px;text-align: center;width: 40px;height: 40px;font-size: 30px;top:230px;font-weight: bold;background: rgba(0,0,0,0.3);}
	#left{left:20px;}
	#right{right: 20px;}
	</style>
</head>
<body>
	<div class="container" id="container">
		<div id="list">
			<img alt="5" src='http://i1.piimg.com/576342/a59848cad8818bd4.jpg'>
			<img alt="1" src='http://i1.piimg.com/576342/9bc3a6f38f9eca10.jpg'>
			<img alt="2" src='http://i1.piimg.com/576342/82507633c9d21ebf.jpg'>
			<img alt="3" src='http://image60.360doc.com/DownloadImg/2013/04/1613/31674132_21.jpg'>
			<img alt="4" src='http://i1.piimg.com/576342/5935e1921d2d5fb0.jpg'>
			<img alt="5" src='http://i1.piimg.com/576342/a59848cad8818bd4.jpg'>
			<img alt="1" src='http://i1.piimg.com/576342/9bc3a6f38f9eca10.jpg'>
		</div>
		<a href="javascript:void(0)" class="arrow" id="left" disabled="false"><</a>
		<a href="javascript:void(0)" class="arrow" id="right" disabled="false">></a>
	</div>

	<script type="text/javascript">
	window.onload = function(){
		var oContainer = document.getElementById('container');
		var oList = document.getElementById('list');
		var oLi = oList.getElementsByTagName('img');
		var oLeft = document.getElementById('left');
		var oRight = document.getElementById('right');
		var oWidth = oContainer.offsetWidth;		
		var animated = false;
		oList.style.left = -oWidth + 'px';

		function animate(offset){
			console.log("offset:" + offset);
			console.log("oWidth:" + oWidth);
			animated = true;
			var newLeft = parseInt(oList.offsetLeft) + offset;
			var time = 300;
			var interval = 10;
			var speed = offset / (time / interval);

			function go(){
				if((speed > 0 && oList.offsetLeft < newLeft) || (speed < 0 && oList.offsetLeft > newLeft)){
					oList.style.left = oList.offsetLeft + speed + 'px';			//动画效果
					setTimeout(go,interval);						//递归
				}else{
					oList.style.left = newLeft + 'px';
					if(newLeft > -oWidth){					//判断图片是第一张还是最后一张
						oList.style.left = -oWidth * 5 + 'px';
					}
					if(newLeft < (-oWidth * 5)){
						oList.style.left = -oWidth + 'px';
					}
					animated = false;
				}
			}
			go();
		}

		oRight.onclick = function(){
			if(animated){
				return ;
			}
			animate(-oWidth);
		}
		oLeft.onclick = function(){
			if(animated){
				return;
			}
			animate(oWidth);
		}
	}
	</script>
</body>
</html>

  

可直接运行

放7张图片的原因是为了动画效果更加平滑

不会造成第一张图片或者最后一张图片过渡效果的时候是空白

本来打算用CSS3来做动画效果

但是发现多次点击后会图片会偏移原来的位置

所以使用原生JavaScript来编写动画

下一篇准备写个百分比自适应布局的轮播图

 

 posted on 2016-10-13 21:19  五只米波丶  阅读(335)  评论(0编辑  收藏  举报