您的位置:首页 > Web前端 > JavaScript

手写JS原生轮播图

2020-07-14 06:30 495 查看

自己写一次留着做念想,以后成码神了再来优化这代码~~~

html代码片段:

<div class="box" onmouseenter="boxMouse()" onmouseleave="boxMove()">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<div class="points">
<span class="active"></span>
<span></span>
<span></span>
<span></span>
</div>
</div>

script代码片段:

<script>
const main = document.getElementsByClassName("box")[0],
points = main.querySelectorAll("span"),
ul = main.querySelector("ul");

let index = 0;

for (let i = 0; i < points.length; i++) {
points[i].addEventListener("click", function() {
index = i
BoxMove(i);
})
}

let interTime = setInterval(() => {
index == points.length - 1 ? index = 0 : index++;
BoxMove(index);
}, 2000)

function BoxMove(index) {
ul.style.left = -600 * index + "px";
activeSpan(index);
}

function activeSpan(index) {
for (let i = 0; i < points.length; i++) {
points[i].className = "";
}
points[index].className = "active";
}

function boxMouse() {
clearInterval(interTime)
}

function boxMove() {
interTime = setInterval(() => {
index == points.length - 1 ? index = 0 : index++;
BoxMove(index);
}, 2000)
}
</script>

css代码片段

<style>
* {
margin: 0;
padding: 0;
}

.box {
width: 600px;
height: 350px;
background-color: turquoise;
margin: 50px auto;
overflow: hidden;
border: 3px solid wheat;
position: relative;
}

.box ul {
width: 999999999px;
height: 350px;
display: flex;
position: absolute;
left: 0;
top: 0;
transition: all 0.5s;
-webkit-transition: all 0.5s;
}

.box ul>li {
width: 600px;
height: 350px;
background-color: tomato;
text-align: center;
line-height: 350px;
color: white;
font-size: 36px;
list-style: none;
}

.box ul>li:nth-child(2) {
background-color: violet;
}

.box ul>li:nth-child(3) {
background-color: yellowgreen;
}

.box ul>li:nth-child(4) {
background-color: blueviolet;
}

.box .points {
position: absolute;
left: 0;
bottom: 0;
background: rgba(255, 255, 255, 0.6);
width: 100%;
height: 70px;
display: flex;
justify-content: center;
align-items: center;
}

.box .points span {
display: block;
width: 20px;
height: 20px;
border-radius: 50%;
margin: 0 15px 0 15px;
background-color: #EBEEF5;
border: 5px solid rgba(255, 255, 255, 0.8);
cursor: pointer;
}

.active {
background-color: coral !important;
}
</style>

最后实现效果


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: