JS横向无限滑动
编辑
233
2023-10-14
实现ul列表的横向鼠标滑动、自动翻动。
<div class="slider-container">
<ul class="slider">
<li class="first">Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
<li>Item 9</li>
<li class="last">Item 10</li>
<li>Item 11</li>
</ul>
</div>
<style>
.slider-container {
position: relative;
width: 100%;
overflow-x: hidden;
white-space: nowrap;
}
.slider {
list-style-type: none;
padding: 0;
margin: 0;
display: flex;
}
.slider li {
flex: 0 0 auto;
width: 200px;
height: 200px;
background-color: #ccc;
margin-right: 10px;
}
</style>
<script>
const slider = document.querySelector('.slider');
const sliderItems = Array.from(slider.children);
const slideWidth = sliderItems[0].offsetWidth + parseInt(getComputedStyle(sliderItems[0]).marginRight);
console.log(sliderItems.length)
// 创建副本
const cloneItems = sliderItems.map(item => item.cloneNode(true));
// 将副本添加到列表的开头和末尾
cloneItems.forEach(item => {
slider.appendChild(item);
});
let currentPosition = 0;
function slideNext() {
console.log(1)
currentPosition--;
slider.style.transform = `translateX(${currentPosition * slideWidth}px)`;
if (currentPosition === -sliderItems.length) {
currentPosition = 0;
slider.style.transform = 'translateX(0)';
}
}
// 设置定时滑动
let interval = setInterval(slideNext, 3000);
// 当鼠标进入滑动区域时,停止定时滑动
slider.addEventListener('mouseenter', () => {
clearInterval(interval);
});
// 当鼠标离开滑动区域时,重新开始定时滑动
slider.addEventListener('mouseleave', () => {
interval = setInterval(slideNext, 3000);
});
slider.addEventListener('wheel', (event) => {
event.preventDefault();
const delta = Math.sign(event.deltaY);
currentPosition -= delta;
slider.style.transform = `translateX(${currentPosition * slideWidth}px)`;
if (currentPosition === -sliderItems.length) {
currentPosition = 0;
slider.style.transform = 'translateX(0)';
} else if (currentPosition === 1) {
currentPosition = -sliderItems.length + 1;
slider.style.transform = `translateX(${currentPosition * slideWidth}px)`;
}
});
// sliderContainer.addEventListener('scroll', () => {
// // 滚动时的逻辑,可根据需要进行自定义
// // 例如,根据滚动位置显示/隐藏前进和后退按钮
//
//
// });
// sliderContainer.addEventListener('wheel', (event) => {
// event.preventDefault();
// sliderContainer.scrollLeft += event.deltaY;
// });
</script>
- 55
-
分享