今天我讲昨天学习的内容(js实现图片的轮播)进行了上机实验
该实验分2步:
1.用js实现简单的图片点击切换。
用js代码实现点击切换
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>图片轮播</title> </head> <body > <input type=button value="返回上一张" onclick="changeImg2()"> <img src="file:///F:/eclipse-workspace/jiaqilianxi/WebContent/image/1.png" id="img1" > <input type=button value="查看下一张" onclick="changeImg3()"> </body> <script> var index=1; function changeImg2() { var img= document.getElementById("img1"); var curIndex=(index+3)%4+1; img.src="file:///F:/eclipse-workspace/jiaqilianxi/WebContent/image/"+curIndex+".png"; index=index+3; } function changeImg3() { var img= document.getElementById("img1"); var curIndex=(index+1)%4+1; img.src="file:///F:/eclipse-workspace/jiaqilianxi/WebContent/image/"+curIndex+".png"; index=index+1; } </script> </html>
2.用计时器进行图片的定时切换。
在这里我是用的是setInterval(“函数代码”,时间间隔)这个计时器。
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>图片轮播</title>
</head>
<body onload="init()">
<img src="file:///F:/eclipse-workspace/jiaqilianxi/WebContent/image/1.png" id="img1" >
</body>
<script>
var index=1;
function changeImg()
{
var img= document.getElementById("img1");
var curIndex=index%4+1;
img.src="file:///F:/eclipse-workspace/jiaqilianxi/WebContent/image/"+curIndex+".png";
index=index+1;
}
function init()
{
setInterval("changeImg()",3000); //用计时器实现每三秒执行一次图片切换函数
}
</script>
效果是实现每三秒自动切换到下一张然后循环