Бесконечная функциональность карусели?CSS

Разбираемся в CSS
Ответить
Anonymous
 Бесконечная функциональность карусели?

Сообщение Anonymous »

Я пытаюсь создать простую карусель во всю ширину, которая бесконечно перемещается по карточкам. Проблема в том, что я не знаю, как заставить его бесконечно зацикливать карты. В настоящее время мне удалось прокрутить назад к исходной карте только после нажатия последней, вместо того, чтобы бесконечно прокручивать назад и вперед к первой/последней карте.
Может ли кто-нибудь дать какую-либо информацию?
HTML:

Код: Выделить всё



Card 1
Card 2
Card 3
Card 4
Card 5
Card 6



Back
Forward


CSS:

Код: Выделить всё

.carousel-container {
width: 100%;
margin: 0 auto;
position: relative;
overflow: hidden;
}

.carousel-wrapper {
overflow: hidden;
width: 100%;
}

.carousel {
display: flex;
transition: transform 0.5s ease-in-out;
will-change: transform;
gap: 60px;
}

.carousel-card {
flex: 0 0 25%;
background: #ff6b6b;
border-radius: 10px;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.5rem;
color: white;
text-align: center;
min-height: 200px;
box-sizing: border-box;
padding: 10px;
}

.carousel-controls {
text-align: center;
margin-top: 20px;
}

.carousel-controls button {
padding: 10px 20px;
font-size: 1rem;
border: none;
background: #4ecdc4;
color: white;
border-radius: 5px;
cursor: pointer;
margin: 0 10px;
transition: background 0.3s ease;
}

.carousel-controls button:hover {
background: #358f89;
}
jQuery:

Код: Выделить всё

jQuery(document).ready(function () {
const $carousel = jQuery('.carousel');
const $carouselWrapper = jQuery('.carousel-wrapper');
const $carouselCards = jQuery('.carousel-card');
const cardCount = $carouselCards.length; // Number of original cards
let currentIndex = 0; // Track current visible card index
const cardWidth = $carouselCards.outerWidth(true); // Width including margins
const totalCardCount = cardCount; // Only the original set of cards (no cloning)

// Function to center the active card in the middle of the container
function centerActiveCard() {
const wrapperWidth = $carouselWrapper.innerWidth();
const visibleWidth = wrapperWidth / 2;
const offset = -(cardWidth + 60) * currentIndex + visibleWidth - cardWidth / 2;
$carousel.css('transform', `translateX(${offset}px)`);
}

centerActiveCard();

// Function to scroll left (Previous button)
function scrollLeft() {
currentIndex--;
if (currentIndex < 0) {
currentIndex = cardCount - 1; // Loop back to the last card of the set
}
centerActiveCard();
}

// Function to scroll right (Next button)
function scrollRight() {
currentIndex++;
if (currentIndex >= cardCount) {
currentIndex = 0; // Loop back to the first card of the set
}
centerActiveCard();
}

// Event listeners for navigation buttons
jQuery('#next').on('click', scrollRight);
jQuery('#prev').on('click', scrollLeft);

// Responsive adjustments
jQuery(window).on('resize', function () {
centerActiveCard();
});
});
Вот CodePen, чтобы вы могли увидеть, что у меня есть:
https://codepen.io/Paul-Moignard/pen /xbKzBNe
Заранее спасибо за помощь!

Подробнее здесь: https://stackoverflow.com/questions/793 ... ctionality
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «CSS»