js無縫滾動

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>無縫滾動</title>
	<style type="text/css">
	ul,li,a,img{
		margin: 0;
		padding: 0;
	}
	a {
		display: inline-block;
		width: 100px;
		height: 50px;
		text-align: center;
		text-decoration: none;
		position: relative;
		top: 100px;
	}
	a:first-child{
		left: 40%;
	}
	a:nth-of-type(2){
		left: 50%;
	}
	#div1{
		margin: 100px auto;
		width: 800px;
		height: 200px;
		background-color: red;

		position: relative;
		overflow: hidden;
	}
	#div1 ul{
		position: absolute;
		top: 0;
		left: 0;
	}
	#div1 ul li{
		width: 200px;
		height: 200px;
		float: left;
		list-style: none;
	}
	</style>
</head>
<body>
	<a href="javascript:;">向左走</a>
	<a href="javascript:;">向右走</a>
	<div id="div1">
		<ul>
			<li><img src="imgR/0.jpg"/></li>
			<li><img src="imgR/1.jpg"/></li>
			<li><img src="imgR/2.jpg"/></li>
			<li><img src="imgR/3.jpg"/></li>
		</ul>
	</div>

	<script type="text/javascript">
	window.onload = function(){
		var oDiv = document.getElementById('div1');
		// 整個ul跑起來
		var oUl = oDiv.getElementsByTagName('ul')[0];
		var aLi = oUl.getElementsByTagName('li');
		var speed = 2;

		oUl.innerHTML += oUl.innerHTML;
		oUl.style.width = aLi[0].offsetWidth * aLi.length + 'px';


		var move = function(){
			// 左走邊界條件
			if (oUl.offsetLeft < - oUl.offsetWidth / 2) {
				oUl.style.left = '0';
			}
			// 右走邊界條件
			if (oUl.offsetLeft > 0) {
				oUl.style.left = - oUl.offsetWidth / 2 + 'px';
			}
			oUl.style.left = oUl.offsetLeft + speed +'px';
		}
		// 自動播放
		var timer = setInterval(move,30);
			// 鼠標移入,關閉定時器
		oDiv.onmouseover = function(){
			clearInterval(timer);
		}
			// 鼠標移走,繼續執行
		oDiv.onmouseout = function(){
			timer = setInterval(move,30);
		}
		// 左走右走
		document.getElementsByTagName('a')[0].onclick = function(){
				speed = -2;
		}
		document.getElementsByTagName('a')[1].onclick = function(){
			speed = 2;
		}
	};
	</script>
</body>
</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章