javascript Realizes Click Picture Switching
- 2021-11-01 23:30:10
- OfStack
It is very common to click to realize the picture switching effect in life. It happens that today's exercise is also to do a picture switching effect. For your reference:
The HTML code is as follows:
<div class="img">
<img src="images/1.jpg" id="myImg" class="myImg" alt=" This is 1.jpg">
<p>
<input type="button" id="pre" class="btn" value=" Upper 1 Zhang ">
<input type="button" id="next" class="btn" value=" Under 1 Zhang ">
</p>
</div>
The CSS code is as follows:
*{
margin: 0;
padding: 0;
}
img{
boder:none;
}
button{
outline: none;
vertical-align: middle;
}
.img{
width: 100%;
margin-left: auto;
margin-right: auto;
margin-top: 20px;
text-align: center;
}
.myImg{
width: 500px;
height: 300px;
}
p{
text-align: center;
}
p .btn{
width: 100px;
height: 30px;
background: #306bbf;
color: #fff;
margin-top: 20px;
margin-bottom: 20px;
}
javascript section:
// Find a label
let myImg = document.getElementById("myImg");
let pre=document.getElementById("pre");
let next=document.getElementById("next");
// Create 1 Array for holding pictures
let arrImg = ["images/1.jpg", "images/1-1.png", "images/3.jpg" ];
// Index subscript of array
let index=0;
// Define event functions
function preImg(event){
index--;
// Implement loop switching
if (index<0)
{
index=arrImg.length-1;
}
myImg.src = arrImg[index];
}
function nextImg(event){
index++;
// Implement loop switching
if (index>arrImg.length-1)
{
index=0;
}
myImg.src = arrImg[index];
}
pre.addEventListener('click',preImg);
next.addEventListener('click',nextImg);