本文实例为大家分享了JavaScript实现左右点击切换图片的具体代码,供大家参考,具体内容如下
效果:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>xxx——空间相册</title>
<link rel="stylesheet" type="text/css" href="./css/Photo_album.css"/>
</head>
<body>
<!-- 相册 -->
<div id="imgmax">
<ul>
<li><img src="./img/brtx.jpeg" ></li>
<li><img src="./img/1.jpeg" ></li>
<li><img src="./img/2.jpeg" ></li>
<li><img src="./img/3.jpeg" ></li>
<li><img src="./img/brtx.jpeg" ></li>
<li><img src="./img/brtx.jpeg" ></li>
</ul>
</div>
</body>
<script src="js/Photo_album.js" type="text/javascript" charset="utf-8"></script>
</html>
CSS:
#imgmax{
width: 600px;
height: 600px;
position: relative;
margin: 20px auto;
}
img{
width: 100%;
height: 100%;
}
ui,li{
margin: 0;
padding: 0;
list-style: none;
float: left;
width: 150px;
height: 150px;
margin-left: 10px;
}
.newdiv{
width: 600px;
height: 600px;
background: #fff;
opacity: 0.5;
}
.newimg{
width: 300px;
height: 300px;
position: absolute;
left: 150px;
top: 50px;
}
.newspan{
position: absolute;
width: 20px;
height: 20px;
left: 450px;
top: 50px;
background: #fff;
text-align: center;
}
.newspanzuo{
position: absolute;
width: 20px;
height: 20px;
left: 100px;
top: 150px;
background: #fff;
text-align: center;
}
.newspanyou{
position: absolute;
width: 20px;
height: 20px;
left: 480px;
top: 150px;
background: #fff;
text-align: center;
}
JavaScript:
var lis = document.getElementsByTagName("li"); //获取li标签
var box = document.getElementById("imgmax"); //获取相册盒子
var index = 0;
//循环遍历li标签
//迭代所有的【li】,用于监听【li】的点击事件
for (let i = 0; i < lis.length; i++) {
lis[i].onclick = function() {
//弹出当前li标签中图片路径
//alert(this.getElementsByTagName("img")[0].src)
//2.创建:div元素,用于遮盖当前所有图片
// box.appendChild()
var j = i;
var newDiv = document.createElement('div');
newDiv.className = "newdiv";
box.appendChild(newDiv)
//3.创建:img元素,用于展示【预览图】
var newImg = document.createElement("img");
newImg.className = "newimg"
newImg.src=this.getElementsByTagName("img")[0].src
box.appendChild(newImg);
//创建 span元素(用于展示“X”,退出预览)
var newSpan = document.createElement("span");
newSpan.innerHTML = "X";
newSpan.className = "newspan";
box.appendChild(newSpan);
newSpan.onclick = function(){
box.removeChild(newDiv);
box.removeChild(newImg);
box.removeChild(Spanz);
box.removeChild(Spany);
box.removeChild(newSpan);
}
// 左边
var Spanz = document.createElement("span");
Spanz.innerHTML = "<";
Spanz.className = "newspanzuo";
box.appendChild(Spanz);
Spanz.onclick = function(){
if (j-->=0) {
newImg.src=document.getElementsByTagName("img")[j].src
} else{
alert("已经是第一张了!!")
}
}
// 右边
var Spany = document.createElement("span");
Spany.innerHTML = ">";
Spany.className = "newspanyou";
box.appendChild(Spany);
Spany.onclick = function(){
if (j++<lis.length-1) {
newImg.src=document.getElementsByTagName("img")[j].src
} else{
alert("已经是第最后一张了!!")
}
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。