JS:滚动到不移动元素



我正在香草JS中构建一个旋转木马,我有两个箭头(指针(,在其中我使用事件委派,并且在父级上有一个侦听器。我正在检查目标类是否包含leftright,然后对其进行适当处理。我正在获取carousel-images元素,该元素上有所有图像,并使用overflow: hidden隐藏它们。根据单击的箭头,我获取carousel-images元素并使用scrollLeft,然后减去/添加子映像的clientWidth。我以前用过它,但现在似乎没有任何效果,我不确定我哪里出了问题。

https://jsfiddle.net/zye01vcn/1/

html

<div>
<div class="carousel-container">
<div class="carousel-images">
<div class="carousel-image">
</div>
<div class="carousel-image two">
</div>
<div class="carousel-image three">
</div>
</div>
<div class="pointers"> 
<span class="left">
<
</span>
<span class="right">
>
</span>
</div>
</div>
</div>
</div>

js

(function (doc) {
//
// Methods
//
function arrowClick(evt) {
if (evt.target.classList.contains('left')) {
carouselImagesContainer.scrollLeft -= carouselImages[0].clientWidth;
} else if (evt.target.classList.contains('right')) {
carouselImagesContainer.scrollLeft += carouselImages[0].clientWidth;
}
}

let testImages = ['https://homepages.cae.wisc.edu/~ece533/images/cat.png', 'https://homepages.cae.wisc.edu/~ece533/images/boat.png', 'https://homepages.cae.wisc.edu/~ece533/images/baboon.png'];
let carouselImagesContainer = document.querySelector('.carousel-images');
let carouselImages = document.querySelectorAll('.carousel-image');
let pointers = document.querySelector('.pointers');
carouselImages.forEach((x,i) => {
let el = document.createElement('img');
el.src = testImages[i];
x.appendChild(el);
})
pointers.addEventListener('click', arrowClick);
})(document);

css

* {
box-sizing: border-box;
}
.carousel-container {
height: 100vh;
background:blue;
width: calc(100% - 20px);
margin: 0 auto;
overflow: hidden;
}
.carousel-images {
display: flex;
width: 10000px;
}
.carousel-image {
width: calc(100% - 40px);
background: green;
height: 100vh;
padding: 20px;
}
.two {
background-color: pink;
}
.three {
background-color: red;
}
span {
font-size: 90px
}
.pointers {
background: transparent;
height: 100%;
position: absolute;
width: 100%;
top: 0;
left: 0;
z-index: 22222222;
display: flex;
align-items: center;
justify-content: space-between;
}

它不起作用的原因是因为

let carouselImagesContainer = document.querySelector('.carousel-images');

应该是

let carouselImagesContainer = document.querySelector('.carousel-container');

你得到的是.转盘图像,而不是.转盘容器.

您还需要更改以下内容,因为这是错误的:

<span class="left">
<
</span>
<span class="right">
>
</span>

收件人:

<span class="left">
&lt;
</span>
<span class="right">
&gt;
</span>

将".cab图像"选择器的样式更改为:

.carousel-images {
display: flex;
width: 100%;
overflow-x: scroll;
}

'溢出-x:滚动;'至关重要。您可以更改"width"属性,但它必须小于其".corrousel image"子项的组合宽度,才能进行滚动(否则不需要滚动,内容只是隐藏(。

尝试这个

.carousel-images {
display: flex;
width: 100%;
overflow: hidden;
}
img{
width:100%
}
.carousel-image {
flex: 0 0 100%;
background: green;
height: 100vh;
padding: 20px;
}

最新更新