如何在轮播的第一张和最后一张幻灯片之间添加平滑过渡?

解释起来有点困难,所以我制作了这个 codepen供参考。我正在尝试使用 vanilla JavaScript 克隆 Bootstrap 轮播,我在幻灯片之间添加了过渡,这对于第一张和最后一张幻灯片之间存在的所有幻灯片都很有效,但是当我单击上一个按钮从第一张幻灯片转到最后一张幻灯片或单击下一个按钮从从最后一张幻灯片到第一张幻灯片,这种过渡行为很奇怪,它沿着中间的所有其他幻灯片移动。

这是我使用的html:


   <div class="carousel-container">

    <div class="carousel-slide">

      <img src="imgs/pc1(1).jpg" class="firstSlide" alt="">

      <img src="imgs/pc1(2).jpg" alt="">

      <img src="imgs/pc1(3).jpg" class="lastSlide" alt="">

    </div>

  </div>

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

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

和 JavaScript:


const carousel_slide = document.querySelector(".carousel-slide");

const carousel_images = document.querySelectorAll(".carousel-slide img");

const prev_btn = document.querySelector("#prevBtn");

const next_btn = document.querySelector("#nextBtn");


let counter = 0;

let size = carousel_images[0].clientWidth;


next_btn.addEventListener("click", () => {

  carousel_slide.style.transition = "all 0.3s ease-in-out";

  counter++;

  if (counter >= carousel_images.length) {

    counter = -1;

    counter++;

  }

  carousel_slide.style.transform = `translateX(${-size * counter}px)`;

});


prev_btn.addEventListener("click", () => {

  carousel_slide.style.transition = "all 0.3s ease-in-out";

  counter--;

  if (counter < 0) {

    counter = carousel_images.length - 2;

    counter++;

  }

  carousel_slide.style.transform = `translateX(${-size * counter}px)`;

});

请帮我解决这个轮播的这些结束幻灯片之间的过渡问题?谢谢


小怪兽爱吃肉
浏览 83回答 1
1回答

慕村225694

首先,复制第一张幻灯片并插入到末尾,然后复制最后一张幻灯片并插入到开头:var lastSlide = carousel_images[slidecount - 1].outerHTML;var firstSlide = carousel_images[0].outerHTML;carousel_slide.insertAdjacentHTML('afterbegin', lastSlide);carousel_slide.insertAdjacentHTML('beforeend', firstSlide);// Shift to the second slide:carousel_slide.style.transform = `translateX(${-size}px)`;当您移至第一张幻灯片之前(最后一张幻灯片的副本)时,您将等待动画结束,然后默默地移至最后一张:if (counter < 0) {&nbsp; setTimeout(() => {&nbsp; &nbsp; counter = carousel_images.length - 1;&nbsp; &nbsp; carousel_slide.style.transition = "none";&nbsp; &nbsp; carousel_slide.style.transform = `translateX(${-size * (counter + 1)}px)`;&nbsp; }, 300);}当您移至最后一张幻灯片(第一张的副本)之后的幻灯片时,您会默默地移至第一张:if (counter >= carousel_images.length) {&nbsp; setTimeout(() => {&nbsp; &nbsp; counter = 0;&nbsp; &nbsp; carousel_slide.style.transition = "none";&nbsp; &nbsp; carousel_slide.style.transform = `translateX(${-size}px)`;&nbsp; }, 300);}工作演示:https://codepen.io/bortao/pen/MWwOVbd
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5