- imgarray是存储图片名的数组,大家把这个改成自己的图片名称就好
- querySelector函数获取img元素,可用getElementByID代替
效果演示 轮播图(手动切图)(点我打开)
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>轮播图</title>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="style.css">
<style>
.number {
float: left;
margin-left: 50%;
margin-top: 100px;
transform: translateX(-50%);
width: 500px;
height: 30px;
text-align: center;
font-size:30px;
}
.box {
width: 900px;
height: 700px;
float: left;
margin-left: 50%;
margin-top: 50px;
transform: translateX(-50%);
background-color: #000;
position: relative;
border: 10px solid #fff;
}
#left,
#right {
font-family: 'icomoon';
width: 50px;
height: 50px;
border-radius: 50%;
background-color: rgb(82, 87, 81, .5);
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 30px;
color: white;
text-align: center;
line-height: 50px;
cursor: pointer;
}
#left{
left: 20px;
}
#right{
right: 20px;
}
</style>
</head>
<body style="background-color:rgba(82, 87, 81, .5)">
<div class="number"></div>
<div class="box">
<img src="" alt="" width="100%" height="100%">
<div id="left"></div>
<div id="right"></div>
</div>
<script>
window.onload = function () {
var i = 0;
var imgarray = ['img/0.jpg', 'img/1.jpg', 'img/2.jpg', 'img/3.jpg', 'img/4.jpg', 'img/5.jpg', 'img/6.jpg', 'img/7.jpg', 'img/8.jpg', 'img/9.jpg', 'img/10.jpg'];
var img = document.querySelector(".box img");
img.src = imgarray[0];
var textNode = document.createTextNode("当前为第1张图片");
var span = document.createElement("span");
var div = document.querySelector(".number")
span.appendChild(textNode);
div.appendChild(span);
var left=document.getElementById("left");
var right=document.getElementById('right');
left.onclick=function(){
i--;
if (i< 0) {
i=imgarray.length-1;
}
span.innerText="当前为第"+(i+1)+"张图片";
img.src = imgarray[i];
}
right.onclick = function () {
i++;
if (i >= imgarray.length) {
i = 0;
}
span.innerText="当前为第"+(i+1)+"张图片";
img.src = imgarray[i];
}
}
</script>
</body>