图片切换
通过点击按钮实现不同图片的切换,同时在选图片的时候按钮的颜色也会跟着
标题样式图:
![](https://i-blog.csdnimg.cn/blog_migrate/131fc4f41b7a501734b78c87280f010b.jpeg)
![](https://i-blog.csdnimg.cn/blog_migrate/b4b12f57885e2eae38bf310a3509a6ce.jpeg)
1、简单的 HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片切换</title>
<style type="text/css">
body{
background: #333;
}
.picture{
width: 463px;
height: 595px;
margin: 0 auto;
position: relative;
}
.picture img{
width: 463px;
height: 595px;
}
.picture ul{
position: absolute;
top: 0;
right:-60px;
}
.picture li{
width: 40px;
height: 40px;
background: #666;
margin: 10px 0;
list-style: none;
}
.picture .active{
background: #FC3;
}
</style>
<script type="text/javascript" src="picture.js"></script>
</head>
<body>
<div class="picture">
<img src="" alt="">
<ul>
</ul>
</div>
</body>
2、JS 文件
window.onload = function () {
// 需要展示的图片以列表显示
imgList = ["img/1.jpg","img/2.jpg","img/3.jpg","img/4.jpg"];
var num = 0;
// 获取相应的节点
var getImg = document.getElementsByTagName("img")[0]; //返回的是一个对象
var getUl = document.getElementsByTagName("ul")[0];
var getLi = getUl.getElementsByTagName("li");
var oldLi = null;
//添加按钮
for(var i=0; i<imgList.length; i++){
getUl.innerHTML += "<li></li>"
}
// 首页图片的显示
getImg.src = imgList[num];
// 首页图片为按钮添加选择的颜色
getLi[num].className = "active";
// 为后面做定点清除按钮颜色使用
oldLi = getLi[num];
// 为按钮添加点击事件
for(var i=0;i<getLi.length;i++) {
// 为每个 li 标签添加索引值,对应 imgList;
getLi[i].index = i;
getLi[i].onclick = function () {
getImg.src = imgList[this.index];
//颜色位置,定点清除,即当前显示,上一个清除
oldLi.className = "";
oldLi = this;
this.className = "active"
}
}
};