首先 新建一个函数
通过函数进行内容的编写
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#outer{
width: 500px;
margin: 50px auto ;
background-color: cornflowerblue;
padding: 10px;
text-align: center;/*//文本居中*/
}
#picture{
width:400px;
}
#picture1{
width: 200px;
}
</style>
<script type="text/javascript">
//点击按钮切换图片
window.onload =function(){
var prev = document.getElementById("prev");
var next = document.getElementById("next");
var img = document.getElementsByTagName("img")[0];
//保存正在保存图片的索引
var index = 0;
//创建一个数组,保存图片的路径
var imgArr = ["img/1.jpg","img/2.jpg","img/3.png"];
var info = document.getElementById("infrom");
prev.onclick = function(){
index--;
if(index<0){index=imgArr.length-1;}
img.src = imgArr[index];
//点击按钮以后应该重新执行一次
info.innerHTML = "一共"+imgArr.length+"张图片,当前第"+(index+1)+"张";
};
next.onclick = function(){
index++;
if(index>imgArr.length-1){index=0}
//要修改元素的属性就是元素。属性 = 属性值;
img.src = imgArr[index];
info.innerHTML = "一共"+imgArr.length+"张图片,当前第"+(index+1)+"张";
};
};
</script>
</head>
<body>
<div id = "outer">
<p id= "infrom"></p>
<img id = "picture" src = "img/1.jpg" alt = "girl" />
<!--<img id = "picture1" src = "img/2.jpg" alt="boy" />-->
<button id = "prev">上一张</button>
<button id = "next">下一张</button>
</div>
</body>
</html>