练习:做一个可以点击按钮切换图片的网页
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin:0;
padding:0;
}
#pic{
width: 500px;
height: 400px;
}
#box{
width: 500px;
margin: 3.125rem auto;
padding: 10px;
background-color:yellow ;
text-align: center;
}
</style>
</head>
<body>
<div id="box">
<p>这里写的提示文字</p>
<img src="img/1.jpg" id="pic">
<button type="button" id="prv">上一张</button>
<button type="button" id="next">下一张</button>
</div>
<script type="text/javascript">
var btn1 = document.getElementById("prv");
var btn2 = document.getElementById("next");
var img = document.getElementsByTagName("img")[0];
picArr = ["img/1.jpg","img/2.jpg","img/3.jpg","img/4.jpg"];
var index = 0;
var info = document.getElementsByTagName("p")[0];
var totalnum = picArr.length;
var inf;
btn1.onclick = function(){
index-=1;
if(index<0){
index = picArr.length-1;
}
img.src = picArr[index];
inf = "共 "+totalnum+" 张图片,当前第"+(index+1)+"张";
info.innerHTML = inf;
};
btn2.onclick = function(){
index+=1;
if(index>picArr.length-1){
index = 0;
}
img.src = picArr[index];
inf = "共 "+totalnum+" 张图片,当前第"+(index+1)+"张";
info.innerHTML = inf;
};
</script>
</body>
</html>