今天给大家带来一个原生的轮播图,如果有什么地方错误,请指出。
这是HTML部分的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div class="index-container">
<ul class="banner">
<li>
<img src="./banner.jpg" alt="">
</li>
<li>
<img src="./banner1.jpg" alt="">
</li>
<li>
<img src="./banner.jpg" alt="">
</li>
<li>
<img src="./banner1.jpg" alt="">
</li>
<li>
<img src="./banner.jpg" alt="">
</li>
<li>
<img src="./banner1.jpg" alt="">
</li>
<li>
<img src="./banner.jpg" alt="">
</li>
</ul>
<p class="left">左</p>
<p class="right">右</p>
</div>
</body>
</html>
我们来给它加个样式
.index-container {
width: 500px;
height: 300px;
overflow: hidden;
position: relative;
ul {
position: absolute;
width: 3500px;
list-style: none;
height: 300px;
padding: 0;
margin: 0;
left: 0;
li {
float: left;
width: 500px;
height: 300px;
img {
width: 100%;
height: 100%;
}
}
}
p {
position: absolute;
width: 20px;
height: 20px;
top: 50%;
margin-top: -10px;
background-color: rgba(0, 0, 0, .5);
}
.left {
left: 20px;
}
.right {
right: 20px;
}
}
这是js部分
<script>
var left = document.getElementsByClassName('left')[0];
var right = document.getElementsByClassName('right')[0];
var banner = document.getElementsByClassName('banner')[0];
var content = document.getElementsByClassName('index-container')[0];
left.onclick = function () {
var str = banner.style.left.slice(0, -2);
banner.style.left = str - 500 + 'px';
if (str <= -3000) {
banner.style.left = 0;
}
}
right.onclick = function () {
var str;
if (banner.style.left === "0px") {
str = -3000;
} else {
str = parseInt(banner.style.left) + 500;
}
banner.style.left = str + "px";
}
var timer = null;
function autoPlay() {
timer = setInterval(function () {
left.onclick();
}, 2000);
}
autoPlay();
content.onmousemove = function () {
clearInterval(timer);
timer = null;
}
content.onmouseleave = function () {
autoPlay();
}
</script>
这样一来就有了一个简易版的轮播图了