javascript轮播图的切换,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<title>1111</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet">
<style>
#control {
width: 400px;
margin: auto;
text-align: center;
}
#container {
height: 400px;
width: 400px;
border: 10px solid #eee;
background: gray;
position: relative;
margin: 10px auto 0;
}
#left,
#right {
width: 40px;
height: 40px;
line-height: 40px;
background: black;
color: white;
border: 2px solid white;
top: 180px;
position: absolute;
text-align: center;
opacity: 0.4;
text-decoration: none;
font-size: 20px;
cursor: crosshair;
}
#left:hover,
#right:hover {
opacity: 0.8;
}
#left {
left: 0;
}
#right {
right: 0;
}
#img {
height: 400px;
width: 400px;
}
#top,
#bottom {
position: absolute;
width: 100%;
height: 30px;
line-height: 30px;
background: black;
opacity: 0.6;
color: white;
text-align: center;
}
#top {
top: 0;
}
#bottom {
bottom: 0;
}
</style>
</head>
<body>
<div id="control">
<input type="button" value="循环播放" id="repeatOK" />
<input type="button" value="顺序播放" id="orderOK" />
</div>
<div id="container">
<a href="javaScript:" id="left"><</a>
<a href="javaScript:" id="right">></a>
<div id="top">图片正在加载...</div>
<div id="bottom">图片正在加载...</div>
<img id="img">
</div>
<script>
function $(id) {
return document.getElementById(id);
}
var arrImg = ["图片/1.jpg", "图片/2.jpg", "图片/3.jpg", "图片/4.jpg",];
var arrBottom = ["图片一", "图片二", "图片三", "图片四",];
var currentIndex = 0;
var isOrder = false;
updateView();
$("left").onclick = function () {
leftClick();
}
$("right").onclick = function () {
rightClick();
}
function leftClick(){
currentIndex--;
if (isOrder && currentIndex < 0) {
alert("已经是第一张了");
currentIndex = 0;
return;
} else if (!isOrder && currentIndex < 0) {
currentIndex = arrImg.length - 1;
}
updateView();
}
function rightClick(){
currentIndex++;
if (isOrder && currentIndex >= arrImg.length) {
alert("已经是最后一张了");
currentIndex = arrImg.length - 1;
return;
} else if (!isOrder && currentIndex >= arrImg.length) {
currentIndex = 0;
}
updateView();
}
function updateView() {
$("top").innerHTML = (currentIndex + 1) + "/" + arrImg.length;
$("bottom").innerHTML = arrBottom[currentIndex];
$("img").src = arrImg[currentIndex];
}
$("repeatOK").onclick = function () {
isOrder = false;
alert("循环播放");
}
$("orderOK").onclick = function () {
isOrder = true;
alert("顺序播放");
}
setInterval(() => {
rightClick();
}, 1000);
</script>
</body>
</html>