一.需求分析
在首页完成对轮播图的效果实现,完成自动切换图片的功能。
二.技术分析
- 获取元素 document.getElementById(“id 名称”)
- 事件(onload)
- 定时操作: setInterval(“changeImg()”,3000);
1.setInterval定时器
三.代码实现
1.切换图片.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>切换图片</title> <style> div{ border: 1px solid white; width:500px ; height: 350px; margin: auto; text-align: center; } </style> <script> var i=1; function changeImg(){ i++; document.getElementById("img1").src="../../img/"+i+".jpg"; if(i==3){ i=0; } } </script> </head> <body> <div> <input type="button" value="下一张" onclick="changeImg()"/> <img src="../../img/1.jpg" width="100%" height="100%" id="img1"/> </div> </body> </html>
2.轮播图.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>轮播图</title>
<style>
#father{
border: 0px solid red;
width: 1300px;
height: 2170px;
margin: auto;
}
</style>
<script>
function init(){
//书写轮图片显示的定时操作
setInterval("changeImg()",3000);
}
//书写函数
var i=0
function changeImg(){
i++;
//获取图片位置并设置src属性值
document.getElementById("img1").src="../img/"+i+".jpg";
if(i==3){
i=0;
}
}
</script>
</head>
<body onload="init()">
<div id="father">
<!--轮播图部分-->
<div id="">
<img src="../img/1.jpg" width="100%" id="img1"/>
</div>
</div>
</body>
</html>