无限循环轮播幻灯片

And*_*ndy 3 html javascript css carousel

更新:07/13

我找到了一种更好的方法来使用名为 的 JS 属性来计算无限滚动,cloneNode并使用它来添加和附加克隆幻灯片以创建无限效果。

我还学习了一种更有效的方法来编写大量此类代码,并且能够防止由于 而发生的事件冒泡transitionend,因此问题已得到解决。

因此,仍然存在两个问题:

我仍然无法将这些点映射到幻灯片上。克隆似乎抛弃了幻灯片阵列,并尝试使用设置点data-对我来说不起作用。

我使用变换来移动幻灯片容器以创建幻灯片,但是如果我缩放窗口,幻灯片容器溢出就会变得可见。查看www.ramtrucks.com,我注意到在重新调整窗口大小时,幻灯片上的变换和宽度属性正在动态变化。我研究了 JS 的调整大小事件,但它们似乎都不与我的代码配合,我认为这是因为我使用的是 Flexbox。所以不知何故我需要同时调整大小和更改弹性属性(我认为?)。

在此输入图像描述

这就是我所在的地方:

// ----- slideshow declarations ----- //
const slideShowContainer = document.querySelector('.slideShow');
const slidesContainer = document.querySelector('.slidesContainer');
const rightBtn = document.querySelector('#slideRight');
const leftBtn = document.querySelector('#slideLeft');
const slideShowInterval = 10000;

let slides = document.querySelectorAll('.slideCard');
let index = 1;
let currentSlide;
let dots;

const firstClone = slides[0].cloneNode(true);
const lastClone = slides[slides.length - 1].cloneNode(true);

firstClone.id = 'firstClone'
lastClone.id = 'lastClone'

slidesContainer.append(firstClone);
slidesContainer.prepend(lastClone);

const slideWidth = slides[index].clientWidth;

slidesContainer.style.transform = `translateX(${-slideWidth * index}px)`;
// -------------------- //


// ----- clone swap ----- // 
const slideCollection = () => document.querySelectorAll('.slideCard');

slidesContainer.addEventListener('transitionend', () => {
  slides = slideCollection();
  if (slides[index].id === firstClone.id) {
    index = 1;
    slidesContainer.style.transition = 'none';
    slidesContainer.style.transform = 'translateX(' + (-slideWidth * index) + 'px)';
  }
  slides = slideCollection();
  if (slides[index].id === lastClone.id) {
    index = slides.length - 2;
    slidesContainer.style.transition = 'none';
    slidesContainer.style.transform = 'translateX(' + (-slideWidth * index) + 'px)';
  }
});
// -------------------- //


// ----- nav buttons ----- //
const moveRight = () => {
  slides = slideCollection();
  if (index >= slides.length - 1) return;
  index++;
  slidesContainer.style.transition = 'transform 0.4s ease-in-out';
  slidesContainer.style.transform = 'translateX(' + (-slideWidth * index) + 'px)';
  closeDisclosure();
}

const moveLeft = () => {
  slides = slideCollection();
  if (index <= 0) return;
  index--;
  slidesContainer.style.transition = 'transform 0.4s ease-in-out';
  slidesContainer.style.transform = 'translateX(' + (-slideWidth * index) + 'px)';
  closeDisclosure();
}

rightBtn.addEventListener('click', moveRight);
leftBtn.addEventListener('click', moveLeft);
// -------------------- //


// ----- selection dots ----- //
const selectDotsGroup = () => document.querySelector('slideNumberDots');
const slideSelect = () => document.querySelectorAll('.slideDot');

const setCurrentSlide = () => {
  slideDots = slideSelect();
  slideDots[index - 1].classList.add('selectedSlide');
};

setCurrentSlide();
// -------------------- //


// ----- slide autoplay ----- //
const autoplay = () => {
  currentSlide = setInterval(() => {
    moveRight();
    closeDisclosure();
  }, slideShowInterval);
}

slidesContainer.addEventListener('mouseenter', () => {
  clearInterval(currentSlide);
})

slidesContainer.addEventListener('mouseleave', autoplay);

autoplay();
// -------------------- //


// ----- disclosure window scripts ----- // 
// open disclosure
let discBtn = document.getElementsByClassName("disclosurePrompt");
let disc;
for (disc = 0; disc < discBtn.length - 0; disc++) {
  discBtn[disc].addEventListener("click", function() {
    this.nextElementSibling.classList.add("discVisible");
  });
}

// close disclosure
let closeBtn = document.getElementsByClassName("fa-times");
let close;
for (close = 0; close < closeBtn.length - 0; close++) {
  closeBtn[close].addEventListener("click", function() {
    var slideDiscWindow = document.querySelectorAll(".discVisible");
    [].forEach.call(slideDiscWindow, function(el) {
      el.classList.remove("discVisible");
    });
  });
}

// close disclosure on slide change
function closeDisclosure() {
  var slideDiscWindow = document.querySelectorAll(".discVisible");
  [].forEach.call(slideDiscWindow, function(el) {
    el.classList.remove("discVisible");
  });
}
// -------------------- //
Run Code Online (Sandbox Code Playgroud)
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: darkgrey;
}

html {
  font-size: 16px;
}

.slideShowWrapper {
  display: flex;
  flex-direction: row;
  position: relative;
  width: 100%;
  height: 40vw;
  margin: 0;
  padding: 0;
  overflow: hidden;
}


/* begin slideshow layout */

.slideShow {
  display: flex;
  justify-content: flex-start;
  flex-direction: row;
  position: relative;
  width: 100vw;
  height: 40vw;
  margin: 0 auto;
  padding: 0;
  overflow: hidden;
}

.slidesContainer {
  display: flex;
  flex: 1 0 100%;
  flex-direction: row;
  width: 100vw;
  height: 40vw;
  margin: 0;
  padding: 0;
}

.slideCard {
  display: flex;
  flex-direction: row;
  flex: 1 0 100%;
  position: relative;
  height: 40vw;
  width: 100vw;
  min-width: 100%;
  margin: 0;
  padding: 0;
  background-color: transparent;
}

.fa-chevron-right {
  display: block;
  opacity: 0;
  font-size: 2.3vw;
  position: absolute;
  top: 50%;
  right: 0;
  color: white;
  margin: 0 5%;
  padding: 0;
  width: auto;
  height: auto;
  z-index: 1;
  background-color: transparent;
  cursor: pointer;
  transform-origin: center;
  transition: transform 0.15s linear, opacity 0.15s linear;
}

.fa-chevron-left {
  display: block;
  opacity: 0;
  font-size: 2.3vw;
  position: absolute;
  top: 50%;
  left: 0;
  color: white;
  margin: 0 5%;
  padding: 0;
  width: auto;
  height: auto;
  z-index: 1;
  background-color: transparent;
  cursor: pointer;
  transition: transform 0.15s linear, opacity 0.15s linear;
}

.fa-chevron-right:hover {
  transform: scale(1.2);
}

.fa-chevron-left:hover {
  transform: scale(1.2);
}

.slideShowWrapper:hover .fa-chevron-right {
  opacity: 1;
}

.slideShowWrapper:hover .fa-chevron-left {
  opacity: 1;
}

.slideNumberDots {
  display: flex;
  flex-direction: row;
  justify-content: center;
  bottom: 0%;
  gap: 0.8vw;
  position: absolute;
  width: 100%;
  z-index: 1;
  margin: 0 auto;
  padding: 1vw;
  background-color: transparent;
  pointer-events: none;
}

.slideDot {
  display: flex;
  height: 0.8vw;
  width: 0.8vw;
  border-radius: 50%;
  border: 0px solid rgb(27, 27, 27);
  margin: 0;
  padding: 0;
  background-color: white;
  transform-origin: center;
  transition: transform 0.2s linear, background-color 0.2s linear;
  pointer-events: all;
}

.slideDot:hover {
  background-color: #1c69d3;
  transform-origin: center;
  transform: scale(1.3);
  cursor: pointer;
}

.slideDot.selectedSlide {
  background-color: #1c69d3;
  transform: scale(1.2);
  transform-origin: center;
  transition: color, transform 0.3s linear;
  outline: 0.15vw solid black;
  border-radius: 50%;
}

.disclosurePrompt {
  display: flex;
  font-family: BMWTypeNext Latin TT, 'DDC Heading Font Face', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  position: absolute;
  color: white;
  font-size: 0.8vw;
  font-weight: 400;
  line-height: 1.25;
  width: fit-content;
  height: fit-content;
  top: 95%;
  left: 5%;
  cursor: pointer;
  z-index: 2;
  user-select: none;
  outline: 1px transparent;
  text-decoration: underline;
}

.disclosurePrompt:hover {
  color: #e4e4e4;
}

.disclosurePrompt:focus {
  color: #e4e4e4;
}

.disclosureContainer {
  visibility: hidden;
  width: 90vw;
  height: auto;
  outline: 1px solid black;
  background-color: rgba(0, 0, 0, 0.95);
  position: absolute;
  margin: 0 auto;
  bottom: 5%;
  left: 5%;
  opacity: 0;
  z-index: 10;
  transition: opacity, top, 0.3s linear;
}

.disclosureContainer.discVisible {
  visibility: visible;
  bottom: 10.5%;
  opacity: 1;
}

.disclosureText {
  font-family: BMWTypeNext Latin TT, 'DDC Heading Font Face', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  color: white;
  line-height: clamp(0.7rem, -0.6rem + 3vw, 0.9rem);
  font-size: clamp(0.5rem, -0.875rem + 3vw, 0.7rem);
  display: block;
  margin: 0 auto;
  padding: 1.5rem 0.5rem 0.5rem 0.5rem;
  text-align: justify;
}

.fa-times {
  display: block;
  color: white;
  font-size: 0.8em;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 12;
  padding: 0.5rem 0.5rem;
  transition: all 0.2s linear;
  cursor: pointer;
}

.fa-times:hover {
  color: #1c69d3;
  transition: all 0.2s linear;
}


/* end slideshow layout */


/* begin images */

.bmw2series {
  content: url("https://i.imgur.com/MABHqGy.jpg");
  width: 100%;
  height: 100%;
  object-fit: cover;
  user-select: none;
}

.bmw3series {
  content: url("https://i.imgur.com/Ggy6iNU.jpg");
  width: 100%;
  height: 100%;
  object-fit: cover;
  user-select: none;
}

.bmwX3 {
  content: url("https://i.imgur.com/ucYCFcu.jpg");
  width: 100%;
  height: 100%;
  object-fit: cover;
  user-select: none;
}

.bmwiX {
  content: url("https://i.imgur.com/bQhvuOY.jpg");
  width: 100%;
  height: 100%;
  object-fit: cover;
  user-select: none;
}

.bmw5series {
  content: url("https://i.imgur.com/sLYH9Gy.jpg");
  width: 100%;
  height: 100%;
  object-fit: cover;
  user-select: none;
}

.bmwPreOwned {
  content: url("https://i.imgur.com/kuOWIEJ.jpg");
  width: 100%;
  height: 100%;
  object-fit: cover;
  user-select: none;
}
Run Code Online (Sandbox Code Playgroud)
<head>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer"
  />
</head>

<body>
  <!-- slideshow wrapper -->
  <div class="slideShowWrapper">
    <!-- slideshow controls -->
    <section id="controls">
      <a><i id="slideRight" class="fa fa-chevron-right" aria-label="Next Slide" data-slider-btn="next"></i></a>
      <a><i id="slideLeft" class="fa fa-chevron-left" aria-label="Previous Slide" data-slider-btn="prev"></i></a>
      <div class="slideNumberDots">
        <a class="slideDot" data-slide="0"></a>
        <a class="slideDot" data-slide="1"></a>
        <a class="slideDot" data-slide="2"></a>
        <a class="slideDot" data-slide="3"></a>
        <a class="slideDot" data-slide="4"></a>
        <a class="slideDot" data-slide="5"></a>
      </div>
    </section>
    <!-- slides container -->
    <div class="slidesContainer">
      <section class="slideCard" id="slide0" data-slide="0">
        <img class="bmw2series" alt="BMW 2 Series" />
        <a class="disclosurePrompt" alt="Disclosure">Important Information</a>
        <div class="disclosureContainer">
          <i class="fa fa-times"></i>
          <p class="disclosureText">
            Through June 30, 2022, lease offer available on new 2022 BMW 228i xDrive Gran Coupe models from participating BMW Centers through BMW Financial Services NA, LLC, to customers who meet BMW Financial Services' credit requirements. Offer not valid in Puerto
            Rico. Monthly lease payments of $459 per month for 36 months is based on an adjusted capitalized cost of $36,155 (MSRP of $40,895, including destination and handling fee of $995, less $3,915 capitalized cost reduction, $0 security deposit,
            and suggested dealer contribution of $825). Actual MSRP and dealer contribution may vary and could affect your monthly lease payment. Cash due at signing includes $3,915 capitalized cost reduction, $459 first month's payment, $925 acquisition
            fee and $0 security deposit. Lessee responsible for insurance during the lease term, excess wear and tear as defined in the lease contract, $0.25/mile over 30,000 miles, plus disposition fee of up to $495 (not to exceed an amount permissible
            by law) at lease end. Not all customers will qualify for security deposit waiver. Tax, title, license, registration and dealer fees are additional fees due at signing. Advertised payment does not include applicable taxes. Purchase option at
            lease end, excluding tax, title and government fees, is $23,719. Offer valid through June 30, 2022 and may be combined with other offers unless otherwise stated. Models pictured may be shown with metallic paint and/or additional accessories.
            Visit your authorized BMW Center for important details.
          </p>
        </div>
      </section>
      <section class="slideCard" id="slide1" data-slide="1">
        <img class="bmw3series" alt="BMW 3 Series" />
        <a class="disclosurePrompt" alt="Disclosure">Important Information</a>
        <div class="disclosureContainer">
          <i class="fa fa-times"></i>
          <p class="disclosureText">
            Through June 30, 2022, lease offer available on new 2022 BMW 228i xDrive Gran Coupe models from participating BMW Centers through BMW Financial Services NA, LLC, to customers who meet BMW Financial Services' credit requirements. Offer not valid in Puerto
            Rico. Monthly lease payments of $459 per month for 36 months is based on an adjusted capitalized cost of $36,155 (MSRP of $40,895, including destination and handling fee of $995, less $3,915 capitalized cost reduction, $0 security deposit,
            and suggested dealer contribution of $825). Actual MSRP and dealer contribution may vary and could affect your monthly lease payment. Cash due at signing includes $3,915 capitalized cost reduction, $459 first month's payment, $925 acquisition
            fee and $0 security deposit. Lessee responsible for insurance during the lease term, excess wear and tear as defined in the lease contract, $0.25/mile over 30,000 miles, plus disposition fee of up to $495 (not to exceed an amount permissible
            by law) at lease end. Not all customers will qualify for security deposit waiver. Tax, title, license, registration and dealer fees are additional fees due at signing. Advertised payment does not include applicable taxes. Purchase option at
            lease end, excluding tax, title and government fees, is $23,719. Offer valid through June 30, 2022 and may be combined with other offers unless otherwise stated. Models pictured may be shown with metallic paint and/or additional accessories.
            Visit your authorized BMW Center for important details.
          </p>
        </div>
      </section>
      <section class="slideCard" id="slide2" data-slide="2">
        <img class="bmwX3" alt="BMW X3" />
        <a class="disclosurePrompt" alt="Disclosure">Important Information</a>
        <div class="disclosureContainer">
          <i class="fa fa-times"></i>
          <p class="disclosureText">
            Through June 30, 2022, lease offer available on new 2022 BMW 228i xDrive Gran Coupe models from participating BMW Centers through BMW Financial Services NA, LLC, to customers who meet BMW Financial Services' credit requirements. Offer not valid in Puerto
            Rico. Monthly lease payments of $459 per month for 36 months is based on an adjusted capitalized cost of $36,155 (MSRP of $40,895, including destination and handling fee of $995, less $3,915 capitalized cost reduction, $0 security deposit,
            and suggested dealer contribution of $825). Actual MSRP and dealer contribution may vary and could affect your monthly lease payment. Cash due at signing includes $3,915 capitalized cost reduction, $459 first month's payment, $925 acquisition
            fee and $0 security deposit. Lessee responsible for insurance during the lease term, excess wear and tear as defined in the lease contract, $0.25/mile over 30,000 miles, plus disposition fee of up to $495 (not to exceed an amount permissible
            by law) at lease end. Not all customers will qualify for security deposit waiver. Tax, title, license, registration and dealer fees are additional fees due at signing. Advertised payment does not include applicable taxes. Purchase option at
            lease end, excluding tax, title and government fees, is $23,719. Offer valid through June 30, 2022 and may be combined with other offers unless otherwise stated. Models pictured may be shown with metallic paint and/or additional accessories.
            Visit your authorized BMW Center for important details.
          </p>
        </div>
      </section>
      <section class="slideCard" id="slide3" data-slide="3">
        <img class="bmwiX" alt="BMW iX" />
        <a class="disclosurePrompt" alt="Disclosure">Important Information</a>
        <div class="disclosureContainer">
          <i class="fa fa-times"></i>
          <p class="disclosureText">
            Through June 30, 2022, lease offer available on new 2022 BMW 228i xDrive Gran Coupe models from participating BMW Centers through BMW Financial Services NA, LLC, to customers who meet BMW Financial Services' credit requirements. Offer not valid in Puerto
            Rico. Monthly lease payments of $459 per month for 36 months is based on an adjusted capitalized cost of $36,155 (MSRP of $40,895, including destination and handling fee of $995, less $3,915 capitalized cost reduction, $0 security deposit,
            and suggested dealer contribution of $825). Actual MSRP and dealer contribution may vary and could affect your monthly lease payment. Cash due at signing includes $3,915 capitalized cost reduction, $459 first month's payment, $925 acquisition
            fee and $0 security deposit. Lessee responsible for insurance during the lease term, excess wear and tear as defined in the lease contract, $0.25/mile over 30,000 miles, plus disposition fee of up to $495 (not to exceed an amount permissible
            by law) at lease end. Not all customers will qualify for security deposit waiver. Tax, title, license, registration and dealer fees are additional fees due at signing. Advertised payment does not include applicable taxes. Purchase option at
            lease end, excluding tax, title and government fees, is $23,719. Offer valid through June 30, 2022 and may be combined with other offers unless otherwise stated. Models pictured may be shown with metallic paint and/or additional accessories.
            Visit your authorized BMW Center for important details.
          </p>
        </div>
      </section>
      <section class="slideCard" id="slide4" data-slide="4">
        <img class="bmw5series" alt="BMW 5 Series" />
        <a class="disclosurePrompt" alt="Disclosure">Important Information</a>
        <div class="disclosureContainer">
          <i class="fa fa-times"></i>
          <p class="disclosureText">
            Through June 30, 2022, lease offer available on new 2022 BMW 228i xDrive Gran Coupe models from participating BMW Centers through BMW Financial Services NA, LLC, to customers who meet BMW Financial Services' credit requirements. Offer not valid in Puerto
            Rico.

Rok*_*jan 8

无限 JavaScript 轮播

\n
    \n
  • 组件应该是可重复使用的。根本不要使用 ID 。请改用类
  • \n
  • 要使组件响应,最简单的方法是设置主包装器,即:font-size: 3vmin;并以单位为后代(子级)定义所有尺寸(字体大小、宽度、高度、位置等)em
  • \n
  • 要使用JS 按(当前)索引的元素突出显示项目符号或幻灯片作为当前目标并使用csomeElement.classList.toggle("is-active", thisIndex === currentIndex)
  • \n
\n

让我们从一个最小的裸机响应式 CSS开始:

\n

\r\n
\r\n
.carousel {\n  position: relative;\n  overflow: hidden;\n}\n\n.carousel-slider {\n  display: flex;\n}\n\n.carousel-slide {\n  flex: 1 0 100%;\n}\n\n.carousel-slide img {\n  display: block;\n  width: 100%;\n  height: 10em;\n  object-fit: cover;\n}\n\n/* That\'s all. Other styles go here */
Run Code Online (Sandbox Code Playgroud)\r\n
<div class="carousel">\n  <div class="carousel-slider">\n    <div class="carousel-slide"><img src="https://via.placeholder.com/800x350/0bf?text=image1" alt="Image 1"></div>\n    <div class="carousel-slide"><img src="https://via.placeholder.com/800x350/fb0?text=image2" alt="Image 2"></div>\n    <div class="carousel-slide"><img src="https://via.placeholder.com/800x350/b0f?text=image3" alt="Image 3"></div>\n  </div>\n</div>
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

这就是关于 CSS 的全部内容。
\n “HTML 中没有导航项目符号?” -你可能会问。不可以,因为这样的 UI 元素应该由 JavaScript 动态创建。不是手动,因为这是一项艰巨的任务。

\n

下面是Carousel 组件的简化和改进的JavaScript :

\n

\r\n
\r\n
// DOM utility functions:\n\nconst el = (sel, par) => (par || document).querySelector(sel);\nconst els = (sel, par) => (par || document).querySelectorAll(sel);\nconst elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);\n\n// Helper functions:\n\nconst mod = (n, m) => (n % m + m) % m;\n\n// Task: Carousel:\n\nconst carousel = (elCarousel) => {\n\n  const animation = 500;\n  const pause = 5000;\n  // Or use something like: const animation = Math.abs(elCarousel.dataset.carouselAnimation ?? 500);\n\n  const elCarouselSlider = el(".carousel-slider", elCarousel);\n  const elsSlides = els(".carousel-slide", elCarouselSlider);\n  const elsBtns = [];\n\n  let itv; // Autoslide interval\n  let tot = elsSlides.length; // Total slides\n  let c = 0;\n\n  if (tot < 2) return; // Not enough slides. Do nothing.\n\n  // Methods:\n  const anim = (ms = animation) => {\n    const cMod = mod(c, tot);\n    // Move slider\n    elCarouselSlider.style.transitionDuration = `${ms}ms`;\n    elCarouselSlider.style.transform = `translateX(${(-c - 1) * 100}%)`;\n    // Handle active classes (slide and bullet)\n    elsSlides.forEach((elSlide, i) => elSlide.classList.toggle("is-active", cMod === i));\n    elsBtns.forEach((elBtn, i) => elBtn.classList.toggle("is-active", cMod === i));\n  };\n\n  const prev = () => {\n    if (c <= -1) return; // prevent blanks on fast prev-click\n    c -= 1;\n    anim();\n  };\n\n  const next = () => {\n    if (c >= tot) return; // prevent blanks on fast next-click\n    c += 1;\n    anim();\n  };\n\n  const goto = (index) => {\n    c = index;\n    anim();\n  };\n\n  const play = () => {\n    itv = setInterval(next, pause + animation);\n  };\n\n  const stop = () => {\n    clearInterval(itv);\n  };\n\n  // Buttons:\n\n  const elPrev = elNew("button", {\n    type: "button",\n    className: "carousel-prev",\n    innerHTML: "<span>Prev</span>",\n    onclick: () => prev(),\n  });\n\n  const elNext = elNew("button", {\n    type: "button",\n    className: "carousel-next",\n    innerHTML: "<span>Next</span>",\n    onclick: () => next(),\n  });\n\n  // Navigation:\n\n  const elNavigation = elNew("div", {\n    className: "carousel-navigation",\n  });\n\n  // Navigation bullets:\n\n  for (let i = 0; i < tot; i++) {\n    const elBtn = elNew("button", {\n      type: "button",\n      className: "carousel-bullet",\n      onclick: () => goto(i)\n    });\n    elsBtns.push(elBtn);\n  }\n\n\n  // Events:\n\n  // Infinite slide effect:\n  elCarouselSlider.addEventListener("transitionend", () => {\n    if (c <= -1) c = tot - 1;\n    if (c >= tot) c = 0;\n    anim(0); // quickly switch to "c" slide (with animation duration 0)\n  });\n\n  // Pause on pointer enter:\n  elCarousel.addEventListener("pointerenter", () => stop());\n  elCarousel.addEventListener("pointerleave", () => play());\n\n  // Init:\n\n  // Insert UI elements:\n  elNavigation.append(...elsBtns);\n  elCarousel.append(elPrev, elNext, elNavigation);\n\n  // Clone first and last slides (for "infinite" slider effect)\n  elCarouselSlider.prepend(elsSlides[tot - 1].cloneNode(true));\n  elCarouselSlider.append(elsSlides[0].cloneNode(true));\n\n  // Initial slide\n  anim(0);\n\n  // Start autoplay\n  play();\n};\n\n// Allows to use multiple carousels on the same page:\nels(".carousel").forEach(carousel);
Run Code Online (Sandbox Code Playgroud)\r\n
*,\n*::before,\n*::after {\n  margin: 0;\n  padding: 0;\n  box-sizing: border-box;\n}\n\n.carousel {\n  position: relative;\n  overflow: hidden;\n  font-size: 2.5vmin;\n}\n\n.carousel-slider {\n  display: flex;\n  transition: 0.3s;\n}\n\n.carousel-slide {\n  flex: 1 0 100%;\n}\n\n.carousel-slide img {\n  display: block;\n  width: 100%;\n  height: 36em;\n  object-fit: cover;\n}\n\n.carousel button {\n  font-size: inherit;\n}\n\n.carousel-prev,\n.carousel-next {\n  position: absolute;\n  top: 50%;\n  transform: translateY(-50%);\n  padding: 1em;\n  border: none;\n  cursor: pointer;\n}\n\n.carousel-prev {\n  left: 2em;\n}\n\n.carousel-next {\n  right: 2em;\n}\n\n.carousel-navigation {\n  position: absolute;\n  bottom: 1em;\n  left: 0;\n  right: 0;\n  display: flex;\n  justify-content: center;\n  gap: 1em;\n}\n\n.carousel-bullet {\n  width: 1em;\n  height: 1em;\n  border: none;\n  background: #fff;\n  cursor: pointer;\n  border-radius: 50%;\n}\n\n.carousel-bullet.is-active {\n  background: #1c69d3;\n}
Run Code Online (Sandbox Code Playgroud)\r\n
<div class="carousel">\n  <div class="carousel-slider">\n    <div class="carousel-slide"><img src="https://via.placeholder.com/800x350/0bf?text=image1" alt="Image 1"></div>\n    <div class="carousel-slide"><img src="https://via.placeholder.com/800x350/fb0?text=image2" alt="Image 2"></div>\n    <div class="carousel-slide"><img src="https://via.placeholder.com/800x350/b0f?text=image3" alt="Image 3"></div>\n    <div class="carousel-slide"><img src="https://via.placeholder.com/800x350/0bf?text=image4" alt="Image 4"></div>\n    <div class="carousel-slide"><img src="https://via.placeholder.com/800x350/0fb?text=image5" alt="Image 5"></div>\n    <div class="carousel-slide"><img src="https://via.placeholder.com/800x350/f0b?text=image6" alt="Image 6"></div>\n  </div>\n</div>
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

幻灯片和项目符号按钮的活动状态是通过使用Fix 负模运算符%固定当前幻灯片索引来处理的。

\n

由于上述内容els(".carousel").forEach(carousel);以及类 \xe2\x80\x94 的使用,您可以在单个页面内拥有无限的轮播 - 每个轮播彼此独立工作。

\n

Fir 视图中的多个元素请参阅此示例

\n

  • 谢谢你!我可能需要一些时间才能与我的项目集成,但您的答案很明确并且您的示例有效,因此我在几分钟后到期之前给了您赏金。:) (2认同)
  • 不客气。如果您遇到集成问题,请告诉我。 (2认同)

Copyright Info

© Copyright 2013-2021 admin@qa.1r1g.com

如未特别说明,本网站的内容使用如下协议:
Creative Commons Atution-NonCommercial-ShareAlike 4.0 International license
.

用以下方式浏览
回到顶部