轮播滑块不会按预期滑动

时间:2020-06-17 18:36:27

标签: javascript html css

我目前正在尝试在html和js中创建轮播。我的代码似乎正确,但是由于某些原因图片无法滑动。我想念什么吗?我可以添加什么? 这是代码:

HTML:

<body>
<div class="carousel-container">
    <div class="carousel-slide">
        <img src="./img/artpic3.jpg" id="lastClone" alt="">
        <img src="./img/artpic1.jpg" alt="">
        <img src="./img/artpic2.jpg" alt="">
        <img src="./img/artpic3.jpg" alt="">
        <img src="./img/artpic1.jpg" id="firstClone" alt="">
    </div>
</div>


<button id="prevBtn">Prev</button>
<button id="nextBtn">Next</button>

<script src="app.js"></script>

JavaScript:

const carouselSlide = document.querySelector('.carousel-slide');
const carouselImages = document.querySelectorAll('.carousel-slide img');


const prevBtn = document.querySelector('#prevBtn');
const nextBtn = document.querySelector('#nextBtn');


let counter = 1;
const size = carouselImages[0].clientWidth;

carouselSlide.style.transform = 'tranlateX(' + (-size * counter) + 'px)';


nextBtn.addEventListener('click', () => {
carouselSlide.style.transition = "transform 0.6s ease-in-out";
counter++;
carouselSlide.style.transform = 'tranlateX(' + (-size * counter) + 'px)';
});
prevBtn.addEventListener('click', () => {
carouselSlide.style.transition = "transform 0.4s ease-in-out";
counter--;
carouselSlide.style.transform = 'tranlateX(' + (-size * counter) + 'px)';
});

CSS:

.carousel-container { 
    width: 70%; margin: auto; border: 5px solid white; overflow: hidden;
}
.carousel-slide {
    display: flex; width: 100%; height: 500px;
}

1 个答案:

答案 0 :(得分:1)

您的轮播有两个问题。

  1. 您将translateX写为tranlateX

  2. carouselImages[0].clientWidth最初为0,由于您已将其分配给常量变量,因此它仍然为0,因此,将counter与{{ 1}}每次单击上一个/下一个按钮。

只需将0更改为(-size * counter),您的轮播就可以正常工作。


检查并运行以下代码段,以获得带有上述更改的轮播的实际示例:

(-carouselImages[0].clientWidth * counter)
const carouselSlide = document.querySelector('.carousel-slide');
const carouselImages = document.querySelectorAll('.carousel-slide img');


const prevBtn = document.querySelector('#prevBtn');
const nextBtn = document.querySelector('#nextBtn');


let counter = 1;

carouselSlide.style.transform = 'translateX(' + (-carouselImages[0].clientWidth * counter) + 'px)';


nextBtn.addEventListener('click', () => {
carouselSlide.style.transition = "transform 0.6s ease-in-out";
counter++;
carouselSlide.style.transform = 'translateX(' + (-carouselImages[0].clientWidth * counter) + 'px)';
});
prevBtn.addEventListener('click', () => {
carouselSlide.style.transition = "transform 0.4s ease-in-out";
counter--;
carouselSlide.style.transform = 'translateX(' + (-carouselImages[0].clientWidth * counter) + 'px)';
});
.carousel-container { width: 70%; margin: auto; border: 5px solid white; overflow: hidden; }
.carousel-slide { display: flex; width: 100%; height: 500px; }