JavaScript图片自动轮播

1.需求

有一组图片, 每隔3秒钟,就去切换一张,最终是一直在不停切换

2.技术分析

​    a.切换图片

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>01切换图片</title>
		<!--
			JS的开发步骤:
			1. 确定事件  点击事件
			2. 通常事件都会出发一个函数
			3. 函数里面通常都会去操作页面元素,做一些交互动作
		-->
		<script>
			function dianji(){
//				alert("准备切换图片");
				var img1 = document.getElementById("img1");
				img1.src="../img/2.jpg";
			}
		</script>
	</head>
	<body>
		<input type="button" value="点击切换图片" onclick="dianji()"/>
		<img src="../img/1.jpg" id="img1"/>
	</body>
</html>

​    b.每个三秒钟做一件事

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>02定时器</title>
		<!--
        	setInterval与setTimeout的区别:
        	setInterval:每隔多少毫秒执行一次函数  取消函数:clearInterval
        	setTimeout:多少毫秒之后执行一次函数     取消函数:clearTimeout
        -->
		<script>
			//window 对象是一个最顶层对象
//			window.setInterval("alert('123');",2000);
			function test(){
				console.log("setInterval 调用了");
			}
//			setInterval("test()",2000);
//			setTimeout("test()",2000);
			var timerID;
			function startDinshiqi(){
				timerID = setInterval("test()",2000);

			}
			
			function stopDingshiqi(){
				clearInterval(timerID);

			}
			
			
				function startDinshiqi2(){

				timerID = setTimeout("test()",3000);
			}
			
			function stopDingshiqi2(){

				clearTimeout(timerID);
			}
		</script>
	</head>
	<body>
		<input type="button" value="setInterval开启定时器" onclick="startDinshiqi()" /><br />
		<input type="button" value="setInterval取消定时器" onclick="stopDingshiqi()"/><br />
		
		<input type="button" value="setTimeout开启定时器" onclick="startDinshiqi2()" /><br />
		<input type="button" value="setTimeout取消定时器" onclick="stopDingshiqi2()"/><br />
	</body>
</html>

3.步骤分析

    1. 确定事件: 文档加载完成的事件 onload
    2. 事件要触发 : init()
    3. 函数里面要做一些事情:(通常会去操作元素,提供交互)
         1. 开启定时器: 执行切换图片的函数 changeImg()
    4.  changeImg()
         1. 获得要切换图片的那个元素

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>03图片自动轮播</title>
		<!--
			1. 确定事件: 文档加载完成的事件 onload
			2. 事件要触发 : init()
			3. 函数里面要做一些事情:(通常会去操作元素,提供交互)
			   1. 开启定时器: 执行切换图片的函数 changeImg()
			4.  changeImg()
			   1. 获得要切换图片的那个元素
		-->
		<script>
			var index = 0;
			
			function changeImg(){
				
				//1. 获得要切换图片的那个元素
				var img = document.getElementById("img1");
				
				//计算出当前要切换到第几张图片
				var curIndex = index%3 + 1;  //0,1,2 
				img.src="../img/"+curIndex+".jpg";  //1,2,3
				//每切换完,索引加1
				index = index + 1;
			}
			
			function init(){
				
				setInterval("changeImg()",1000);
			}
			
		</script>
	</head>
	<body onload="init()">
		<img src="../img/1.jpg" width="100%" id="img1"/>
	</body>
</html>


 

猜你喜欢

转载自blog.csdn.net/mqingo/article/details/83759443