gpt4 book ai didi

javascript - Vanilla JavaScript 中的轮播 - 滑动所有图片而不是一张

转载 作者:太空宇宙 更新时间:2023-11-04 15:28:40 28 4
gpt4 key购买 nike

请问你能帮我吗,如何在 Vanilla JS 中制作轮播,它会同时显示 3 张图片,当我单击下一步按钮时,它会滑动,所以第一个(左)将滑出屏幕,然后向右滑动会滑入新的吗?我尝试过这样做,但是我将所有 div 都堆放在下面,并且它同时滑动所有 div。

所有幻灯片均已在 CSS 中设置:

.slide {
display: inline-block;
}

这是 Codepen 上的工作示例:https://codepen.io/vlastapolach/pen/zzmMOW

这是完整的 JS 代码:

var Carousel = function (frameSelector, sliderSelector, slidesSelector, btnLeftSelector, btnRightSelector) {
//A variable to store the position of the slides
var leftPosition = 0;
var frame = document.querySelector(frameSelector);
var slides = document.querySelectorAll(slidesSelector);
//Get the number of slides in the slider
var slidesNumber = slides.length;
var leftButton = document.querySelector(btnLeftSelector);
var rightButton = document.querySelector(btnRightSelector);
var slider = document.querySelector(sliderSelector);

//Add classes to frame and slider divs
frame.classList.add('frame');
slider.classList.add('slider');

//Event listeners for when the user clicks on the arrows
leftButton.addEventListener("click", function() {
carousel.previous();
});

rightButton.addEventListener("click", function() {
carousel.next();
});

//Function that moves the slides left or right depending on variable value
//Moves to the next slide if value is -1, moves to the previous is value is 1
var moveSlide = function (value) {
leftPosition += value*100;
slider.style.left = leftPosition + '%';
};

return {
//Function to move to next slide
next: function() {
if(leftPosition > (slidesNumber-1)*-100)
{
moveSlide(-1);
} else {
leftPosition = 0;
slider.style.left = leftPosition + '%';
}
},
//Function to go to previous slide
previous: function() {
if(leftPosition !== 0) {
moveSlide(1);
} else {
leftPosition = (slidesNumber-1)*-100;
slider.style.left = leftPosition + '%';
}
}
};
};

//Create new instance of Carousel
var carousel = new Carousel('#frame', '#slider', '#slider .slide', '.arrowLeft', '.arrowRight');

请问您知道如何让它发挥作用吗?谢谢!

最佳答案

谢谢,不过我自己解决了。

我必须在顶部容器中添加:

overflow: hidden;

以及 slider 容器:

display: inline-flex;

因此它将所有 div 堆叠在一行中, slider 终于可以工作了。

关于javascript - Vanilla JavaScript 中的轮播 - 滑动所有图片而不是一张,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44998900/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com