有两个很重要的知识点:
(1)getElementById
(2)substring(0, Object.indexOf(“px”));获取数字
(3)切换页面:getElementById.style.float = "right"来修改页面浮动,进而改变图片出现位置。
(4) window.setInterval(Switch, 100);设置每XXms执行一次函数。
<html>
<head>
<title>$Title$</title>
<script type="text/javascript">
var x = 1;
var y = 2;
var maxpicNum = 3;
var timeOut = 30;
var temp = 30;
function Switch() {
var leftObj = document.getElementById("pic" + x);
var rightObj = document.getElementById("pic" + y);
var leftWidth = leftObj.style.width;
var leftWidthNum = leftWidth.substring(0, leftWidth.indexOf("px"));
var rightWidth = rightObj.style.width;
var rightWidthNum = rightWidth.substring(0, rightWidth.indexOf("px"));
if (leftWidthNum > 0) {
leftObj.style.width = (Number(leftWidthNum) - 50) + "px";
rightObj.style.width = (Number(rightWidthNum) + 50) + "px";
} else {
if (temp == 0) {
temp = timeOut;
x = x == maxpicNum ? 1 : x + 1;
y = y == maxpicNum ? 1 : y + 1;
if (y == 1) {
document.getElementById("pic1").style.float = "right";
} else {
document.getElementById("pic1").style.float = "left";
}
} else {
temp--;
}
}
}
function autoSwich() {
//setInterval设置暂停时间300ms
window.setInterval(Switch, 100);
}
</script>
</head>
<body>
<div style="width: 400px;float: left;height: 280px;background-color: gray;">
<div id="pic1" style="width: 400px;height: 280px;float: left;">
<img style="width: 100%;height: 100%" src="imgs/pic1.png" alt="第一张">
</div>
<div id="pic2" style="width: 0px;height: 280px;float: left;">
<img style="width: 100%;height: 100%" src="imgs/pic2.png" alt="第二张"></div>
<div id="pic3" style="width: 0px;height: 280px;float: left;">
<img style="width: 100%;height: 100%" src="imgs/pic3.png" alt="第三张"></div>
</div>
<input type="button" value="Switch" onclick="Switch()"/>
<input type="button" value="AutoSwitch" onclick="autoSwich()"/>
</body>
</html>