<!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: 600px;
height: 200px;
padding: 10px;
margin: 20px auto;
border: 1px solid #ccc;
}
.wrapper {
width: 600px;
height: 200px;
position: relative;
overflow: hidden;
}
.box img {
width: 300px;
height: 200px;
display: block;
}
.box ul {
width: 600%;
height: 200px;
position: absolute;
left: 0px;
}
.box li {
list-style: none;
float: left;
}
</style>
</head>
<body>
<div class="box">
<div class="wrapper">
<ul class="imgs">
<li>
<img src="./imgs/a.jpg" alt="">
</li>
<li>
<img src="./imgs/b.jpg" alt="">
</li>
<li>
<img src="./imgs/c.jpg" alt="">
</li>
<li>
<img src="./imgs/d.jpg" alt="">
</li>
</ul>
</div>
</div>
<script>
// 需求分析
// 我要写一个构造函数 构造函数生成一个对象可以根据我的css选择器
// 把我指定的元素进行无缝滚动
// 当我的鼠标放入的时候滚动停止
// 鼠标移出继续滚动
class SwiperLoop {
constructor(selector) {
// 记录无缝滚动的容器
let container = document.querySelector(selector)
// 包裹滚动层的盒子
this.wrapper = container.querySelector('.wrapper')
console.log(this.wrapper)
// 实例对象上有一个记录滚动的ul
this.ul = container.querySelector('ul')
this.liS = this.ul.children
this.timer = null
this.init()
}
init() {
for (let i = 0; i < 2; i++) {
let newLi = this.liS[i].cloneNode(true)
this.ul.appendChild(newLi)
}
this.move()
this.addMouseEnterEvent()
this.addMouseLeaveEvent()
}
move() {
this.timer = setInterval(() => {
this.ul.style.left = this.ul.offsetLeft - 2 + 'px'
if (this.ul.offsetLeft <= -1200) {
this.ul.style.left = 0
}
}, 20)
}
addMouseEnterEvent() {
// console.log(this.wrapper)
this.wrapper.onmouseenter = () => {
clearInterval(this.timer)
}
}
addMouseLeaveEvent() {
this.wrapper.onmouseleave = () => {
this.move()
}
}
}
new SwiperLoop('.box')
</script>
</body>
</html>
标签:box,滚动,轮播,04,wrapper,height,ul,CSS,200px
From: https://blog.csdn.net/m0_64904350/article/details/140549196