老师问个问题
<!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;
}
div {
width: 500px;
height: 300px;
margin: 0px auto;
position: relative;
overflow: hidden;
}
.imgbox {
width: 3000px;
position: absolute;
left: 0;
transition: all .3s linear 0s;
}
img {
width: 500px;
height: 300px;
float: left;
}
a {
position: absolute;
color: #fff;
font-size: 20px;
width: 50px;
height: 50px;
top: 50%;
margin-top: -25px;
background-color: rgba(109, 107, 107, 0.8);
text-align: center;
line-height: 50px;
text-decoration: none;
}
a.right {
right: 0;
}
a.left {
left: 0;
}
</style>
</head>
<body>
<div id="box">
<div id="imgbox" class="imgbox">
<img src="img/1.jpg" alt="">
<img src="img/2.jpg" alt="">
<img src="img/3.jpg" alt="">
<img src="img/4.jpg" alt="">
<img src="img/1.jpg" alt="">
</div>
<a href="#" class="right" id="r">👉</a>
<a href="#" class="left" id="l">👈</a>
</div>
</body>
<script>
var imgbox = document.getElementById('imgbox');
var imgs = imgbox.querySelectorAll('img');
var r = document.getElementById('r');
var l = document.getElementById('l');
var left = 0;
var index = 0;
var lock = true;
var time;
//自动轮播
function fun() {
clearInterval(time)
time = setInterval(function () {
aaa()
}, 1000)
}
fun()
//鼠标进入移出
imgbox.onmouseenter = function () {
clearInterval(time)
}
imgbox.onmouseleave = function () {
fun()
}
r.onmouseenter = function () {
clearInterval(time)
}
l.onmouseenter = function () {
clearInterval(time)
}
r.onmouseleave = function () {
fun()
}
l.onmouseleave = function () {
fun()
}
//右按钮
r.onclick = function () {
if (!lock) return;
if (index == 0) {
imgbox.style.transition = 'none'
imgbox.style.left = -4 * 500 + 'px'
index = 4
setTimeout(function () {
imgbox.style.transition = 'all .3s linear 0s'
index--
imgbox.style.left = -index * 500 + 'px'
}, 0)
} else {
index--
imgbox.style.left = -index * 500 + 'px'
}
lock = false;
setTimeout(function () {
lock = true;
}, 500)
}
//左按钮
var aaa = l.onclick = function () {
if (!lock) return;
index++;
if (index > 3) {
setTimeout(function () {
imgbox.style.transition = 'none'
imgbox.style.left = 0
index = 0;
}, 300)
}
lock = false;
imgbox.style.transition = 'all .3s linear 0s'
imgbox.style.left = index * -500 + 'px'
setTimeout(function () {
lock = true;
}, 500)
}
</script>
</html>你好老师,我加了自动轮播的函数,但是要写好几个鼠标进入移出的函数,看着很臃肿的感觉。会有优化的学习吗?
10
收起
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星