<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 500px;
height: 300px;
margin: 0 auto;
margin-top: 10%;
position: relative;
border: 1px solid #000;
}
.left {
width: 20px;
height: 50px;
line-height: 50px;
position: absolute;
top: 40%;
background-color: rgb(240, 240, 235, .5);
}
.right {
width: 20px;
height: 50px;
line-height: 50px;
position: absolute;
right: 0;
top: 40%;
background-color: rgb(240, 240, 235, .5);
}
img {
width: 500px;
height: 300px;
}
</style>
</head>
<body>
<div class="box" id="box">
<button class="left">《</button>
<button class="right">》</button>
</div>
<script>
var arr = [
'https://img2.baidu.com/it/u=1003272215,1878948666&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800',
'https://img2.baidu.com/it/u=3038223445,2416689412&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800',
'https://img2.baidu.com/it/u=2969169350,1551254405&fm=253&fmt=auto&app=120&f=PNG?w=1280&h=800',
'https://img0.baidu.com/it/u=3004830896,1136484098&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800'
];
const box = document.getElementById("box")
const btn = document.querySelectorAll("button")
var index = 2
let lock = true
var timer
for (let i = 0; i < arr.length; i++) {
var img = document.createElement("img")
img.src = arr[i]
box.appendChild(img)
img.style.display = "none"
}
box.children[2].style.display = "block"
const imgs = document.querySelectorAll("img");
let i = setInterval(function () {
box.children[index].style.display = "none"
if (index == 5) {
index = 2
} else {
index++
}
box.children[index].style.display = "block"
box.onmouseenter = function () {
btn[0].style.display = "block"
btn[1].style.display = "block"
clearInterval(i)
}
box.onmouseleave = function () {
btn[0].style.display = "none"
btn[1].style.display = "none"
i = setInterval(function () {
box.children[index].style.display = "none"
if (index == 5) {
index = 2
} else {
index++
}
box.children[index].style.display = "block"
}, 1000)
}
}, 1000)
var temp = 0
btn[1].onclick = function () {
imgs[temp].style.display = "none"
if (temp == 3) {
temp = 0
} else {
temp++
}
imgs[temp].style.display = "block"
}
btn[0].onclick = function () {
imgs[temp].style.display = "none"
if (temp == 0) {
temp = 3
} else {
temp--
}
imgs[temp].style.display = "block"
}
// 按钮进入和离开事件
/* box.onmouseenter = function () {
btn[0].style.display = "block"
btn[1].style.display = "block"
}
box.onmouseleave = function () {
btn[0].style.display = "none"
btn[1].style.display = "none"
} */
</script>
</body>
</html>