
и это код Js:
Код: Выделить всё
jQuery(document).ready(function($) {
const carousel = $('.carousel-custom');
const items = $('.carousel-item');
let focusedIndex = 5; // Start with the fourth item focused
// Function to center the focused item
function centerItem(index) {
const item = $(items[index]);
const carouselWidth = carousel.width();
const itemWidth = item.outerWidth(true);
// Calculate the scroll position to center the item
const scrollPosition = 135;
// Debugging output
console.log('Focused Index:', index);
console.log('Item Position:', item.position().left);
console.log('Carousel Width:', carouselWidth);
console.log('Item Width:', itemWidth);
console.log('Scroll Position:', scrollPosition);
// Ensure scroll position is not negative or out of bounds
if (scrollPosition < 0) {
carousel.animate({ scrollLeft: 0 }, 300);
} else if (scrollPosition + carouselWidth > carousel[0].scrollWidth) {
carousel.animate({ scrollLeft: carousel[0].scrollWidth - carouselWidth }, 300);
} else {
// Animate the scroll to the calculated position
carousel.animate({ scrollLeft: scrollPosition }, 300);
}
}
// Function to set the focus on an item by index
function setFocus(index) {
// Remove focused class from all items
items.removeClass('focused');
// Add focused class to the specified item
$(items[index]).addClass('focused');
// Center the focused item
centerItem(index);
}
// Function to trigger a click on the focused item
function triggerClick(index) {
items.eq(index).trigger('click');
}
// Set initial focus on the third item and trigger a click
setFocus(focusedIndex);
triggerClick(focusedIndex); // This simulates a click on the third item
// Click event for carousel items
items.on('click', function() {
const clickedIndex = $(this).index();
console.log('Clicked Index:', clickedIndex); // Debugging output
setFocus(clickedIndex); // Focus on clicked item
});
});
Подробнее здесь: https://stackoverflow.com/questions/790 ... t-shifting
Мобильная версия