Specific implementation steps:
2.1 Click the right arrow to switch pictures back in sequence. If you switch to the last picture, return to the first picture 1--2--3--4--1
2.1.1 Get element button p img
2.1.2 Add event Add button
2.1.3 Switch to the next picture
2.1.4 I don’t know which picture it is. Assume n = 1
2.1.5 Update the address of img img.src = '';
2.1.6 After the picture is +1, determine whether it is the last picture. If n == 5 n = 1
2.2 Click the left arrow to switch the pictures forward in sequence. If it is the first picture, go back to the last picture 1--4--3--2--1
2.2.1 Get element button p img
2.2.2 Add event Add button
2.2.3 Switch to the previous picture
2.2.4 Get the current picture through n
2.2.5 Update the address of img img.src = '';
2.2.6 After picture-1, determine whether it is already the first picture. If n == 0 n = 4
<style>
* {
padding: 0;
margin: 0;
}
.wrap {
position: relative;
width: 700px;
height: 400px;
margin: 10px auto;
}
.wrap p {
color: #fff;
text-align: center;
line-height: 20px;
background-color: #000;
}
.wrap img {
vertical-align: middle;
width: 100%;
height: 360px;
}
.wrap button {
width: 30px;
height: 30px;
font-size: 20px;
color: #fff;
background: rgba(0, 0, 0, 0.5);
text-align: center;
line-height: 30px;
outline: none;
position: absolute;
top: 50%;
margin-top: -15px;
}
.btn1 {
right: 0;
}
.btn2 {
left: 0;
}
</style>
<div class="wrap">
<p>1/4</p>
<img src="./img1.jpg" alt="">
<p>动漫1</p>
<button class="btn1">></button>
<button class="btn2"><</button>
</div>
<script>
//1、获取元素 按钮 p img
var img = document.getElementsByTagName('img')[0];
var btns = document.getElementsByTagName('button');
var ps = document.getElementsByTagName('p');
console.log(btns, img, ps);
//4、不知道照片处于第几张 假设一个变量存初始值
var n = 1;
//2、添加事件 加给按钮 btns
btns[0].onclick = function () {
//3、写具体代码操作
n++;
console.log(n);
if (n == 5) {
n = 1
}
//5、图片切换到下一张
img.src = './img' + n + '.jpg'
//获取p标签内容
//设置p标签内容里面的数字
ps[0].innerHTML = n + '/4';
ps[1].innerHTML = '动漫' + n;
}
btns[1].onclick = function () {
//3、写具体代码操作 图片切换到下一张
n--;
console.log(n);
if (n == 0) {
n = 4
}
//5、切换图片
img.src = './img' + n + '.jpg'
//获取p标签内容
//设置p标签内容里面的数字
ps[0].innerHTML = '' + n + '/4';
ps[1].innerHTML = '动漫' + n;
}
</script>
Effect: