<!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>swiperNormal</title>
<style>
* {
padding: 0;
margin: 0;
}
html,
body {
height: 100vh;
}
.swiper-box {
display: inline-block;
box-sizing: border-box;
width: 100%;
height: 90%;
padding: 10px;
}
.item {
display: inline-block;
width: 100%;
height: 100%;
display: none;
background-size: cover;
}
.item-active {
display: inline-block;
}
.btns {
display: flex;
justify-content: space-around;
align-items: center;
}
.btns button {
font-style: italic;
/**字体斜体*/
padding: 10px;
border-radius: 5px;
border: none;
color: #4760fa;
}
.btns button:hover {
cursor: pointer;
color: #bbd0fd;
background-color: #4760fa;
border: none;
}
</style>
</head>
<body>
<div class="swiper-box">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<div class="btns">
<button class="prev">prev</button>
<button class="next">next</button>
</div>
<script>
var items = document.getElementsByClassName('item')
var count = Math.floor(items.length / 2)
var prevBtn = document.getElementsByClassName('prev')[0];
var nextBtn = document.getElementsByClassName('next')[0];
var interval, intervalTime = 1000;
for (var i = 0; i < items.length; i++) {
// 获取当前item
let item = items[i];
// 设置背景图片
item.style.backgroundImage = 'url(./img/' + (i + 1).toString() + '.png)';
}
function move(conf) {
if (conf < 0) conf = items.length - 1;
if (conf > items.length - 1) conf = 0;
count = conf;
for (let index = 0; index < items.length; index++) {
let item = items[index];
if (index == count) {
item.classList.add('item-active')
} else {
item.classList.remove('item-active')
}
}
}
function bindEvents() {
prevBtn.addEventListener('click', () => { prev(); });
nextBtn.addEventListener('click', () => { next(); });
}
function timer() {
clearInterval(interval);
interval = setInterval(() => {
move(++count)
}, intervalTime)
}
function init() {
move(Math.floor(items.length / 2));
bindEvents();
timer();
}
function prev() {
console.log('prev');
move(--count);
timer();
}
function next() {
move(++count);
timer();
}
init()
</script>
</body>
</html>
轮播原生。
于 2023-11-27 17:34:43 首次发布