简体   繁体   English

在同一个脚本上运行多个 vanilla JS 轮播

[英]Multiple vanilla JS carousels running on same script

I want to have two independent image carousels, stacked on top of each other.我想要两个独立的图像轮播,相互堆叠。 I thought making both of them with the same class would make them both work from the same script - but only the first one scrolls.我认为用相同的 class 制作它们会使它们都使用相同的脚本 - 但只有第一个卷轴。 Is it because of the array variable?是因为数组变量吗?

window.onload = function(){
    var track = document.querySelector('.carousel_track');
    var slides = Array.from(track.children);

function setSlidePosition (slide, index) {
    slide.style.left = slideSize * index + 'px';
};
slides.forEach(setSlidePosition);

function moveToSlide (track, currentSlide, targetSlide){
    track.style.transform = 'translateX(-' + targetSlide.style.left + ')';
    currentSlide.classList.remove('current-slide');
    targetSlide.classList.add('current-slide');
};

Here is the codepen: https://codepen.io/beseu/pen/RwxebYy这是代码笔: https://codepen.io/beseu/pen/RwxebYy

The first one is the only one that is scrolling as that is the one returned from document.querySelector('.carousel_track');第一个是唯一滚动的,因为它是从document.querySelector('.carousel_track');返回的那个. . querySelector will only return the first match ( null if no match is found). querySelector将仅返回第一个匹配项(如果未找到匹配项, null )。 See https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector for further reference.有关进一步参考,请参阅https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

You could tweak things a bit by using querySelectorAll ( https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll ) to get all matching elements.您可以使用querySelectorAll ( https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll ) 来稍微调整一下以获取所有匹配的元素。 With the HTML provided in the CodePen, you could query for all carousels with .carousel , and set each one up using most of your existing JS.使用 CodePen 中提供的 HTML,您可以使用.carousel查询所有轮播,并使用现有的大部分 JS 设置每个轮播。 Here's an example - https://codepen.io/brianmarco/pen/WNdaNov .这是一个示例 - https://codepen.io/brianmarco/pen/WNdaNov

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM