Web站点上的幻灯片每次向用户显示一个图像,并且让用户能够控制显示图像的进度(既可以向前,也可以向后)。javascript向用户提供所需的交互控制能力。脚本1显示了必须的HTML,脚本2显示了在页面上添加幻灯片所需的javascript。
脚本1:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Image Slideshow</title>
<script type="text/javascript" src="script09.js"></script>
</head>
<body bgcolor="#FFFFFF">
<div align="center">
<h1>Welcome, Robot Overlords!</h1>
<img src="images/robot1.jpg" id="myPicture" width="200" height="400" alt="Slideshow" />
<h2><a href="previous.html" id="prevLink"><< Previous</a> <a href="next.html" id="nextLink">Next >></a></h2>
</div>
</body>
</html>
脚本2:
window.onload = initLinks;
var myPix = new Array("images/robot1.jpg","images/robot2.jpg","images/robot3.jpg");
var thisPic = 0;
function initLinks() {
document.getElementById("prevLink").onclick = processPrevious;
document.getElementById("nextLink").onclick = processNext;
}
function processPrevious() {
if (thisPic == 0) {
thisPic = myPix.length;
}
thisPic--;
document.getElementById("myPicture").src = myPix[thisPic];
return false;
}
function processNext() {
thisPic++;
if (thisPic == myPix.length) {
thisPic = 0;
}
document.getElementById("myPicture").src = myPix[thisPic];
return false;
}
经过分析,其实该函数很简单,无非新创建了两个函数processPrevious和processNext,一个实现向前,一个实现向后。需要注意的是该脚本实现的幻灯片是循环式的,也就是说图片到了末尾,就可以回到开头,一次需要注意判断thePic和myPix.length的关系。