上周学习了DOM,学习了怎样进行图片的切换,下面是详细代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#one{
width: 500px;
text-align: center;
margin: 50px auto;
background-color: greenyellow;
padding: 10px;
/*font-size: 30px;*/
}
img{
width: 500px;
height: 500px;
}
</style>
<script type="text/javascript">
window.onload = function(){
//获取prev标签
var prev = document.getElementById("prev");
//获取next标签
var next = document.getElementById("next");
//获取img标签
var img = document.getElementsByTagName("img")[0];
/*
* 要切换图片就是修改img标签的src属性
*/
//将所有的img放在一个数组
var imgArr = ["../img/3_03.jpg" , "../img/3_04.jpg" , "../img/3_05.jpg" , "../img/3_06.jpg"];
//创建一个变量,来保存当前正在显示图片的索引
var index = 0;
//获取id为info的p元素
var info = document.getElementById("info");
//设置提示文字
info.innerHTML = "一共"+(imgArr.length)+"张图片,当前第"+(index+1)+"张";
//为prev绑定单机函数
prev.onclick = function (){
/*
* 切换上一张,索引自减
*/
index--;
if(index<0){
index = imgArr.length-1;
}
img.src = imgArr[index];
info.innerHTML = "一共"+(imgArr.length)+"张图片,当前第"+(index+1)+"张";
};
//为next绑定单机函数
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="one">
<p id = info></p>
<img src="../img/3_03.jpg" alt="雪人"/>
<button id = "prev">上一张</button>
<button id = "next">下一张</button>
</div>
</body>
</html>