Anonymous
Карусель неправильно перемещается при пролистывании или нажатии на ползунок (следующий/предыдущий)
Сообщение
Anonymous » 27 дек 2024, 07:07
Я только что закончил создание карусели, над которой работал, которая использует пролистывание/касание, а также такие элементы управления, как предыдущая/следующая, для управления каруселью. Прямо сейчас у меня возникла проблема, связанная с поведением карусели. По сути, я пытаюсь заставить его скользить один за другим. Вот пример кода, над которым я работал. Сейчас кажется, что он скользит на 2 или 3 в зависимости от того, сколько каруселей я разместил.
У меня также возникла проблема с тем, чтобы сделать его отзывчивым.
Код: Выделить всё
function fCarousel() {
// var activeSlide = 0;
// $('.faculty-carousel').attr('data-slide', '0');
var viewPortSize = $(window).width(),
facultyPanel = $('.faculty-carousel .faculty-items li'),
profileCount = facultyPanel.length,
activeSlide = 0,
carousel = $('.faculty-carousel .faculty-items');
$('.faculty-carousel').attr('data-slide', '0');
//Set Panel Size based on viewport
if (viewPortSize 0) {
// Decremement current slide
currentSlide--;
// Assign CSS position to clicked slider
var transformPercentage = -1 * currentSlide / facultyProfileCount * 100;
carousel.css('transform', 'translateX(' + transformPercentage + '% )');
// Update data-slide attribute
carouselWrapper.attr('data-slide', currentSlide);
activeSlide = currentSlide;
}
});
$('.next').on('click', function(e) {
event.stopPropagation();
// store variable relevent to clicked slider
var carouselWrapper = $(this).closest('.faculty-carousel'),
facultyProfilePanel = carouselWrapper.find('.faculty-items li'),
facultyProfileCount = facultyProfilePanel.length,
viewPortSize = $(window).width(),
carousel = carouselWrapper.find('.faculty-items'),
position = 0,
currentSlide = parseInt(carouselWrapper.attr('data-slide'));
// Check if dataslide is less than the total slides
if (currentSlide < facultyProfileCount - 1) {
// Increment current slide
currentSlide++;
// Assign CSS position to clicked slider
var transformPercentage = -1 * currentSlide / facultyProfileCount * 100;
carousel.css('transform', 'translateX(' + transformPercentage + '% )');
// Update data-slide attribute
carouselWrapper.attr('data-slide', currentSlide);
activeSlide = currentSlide;
}
})
$('.faculty-carousel .faculty-items').each(function() {
// create a simple instance
// by default, it only adds horizontal recognizers
var direction;
var touchSlider = this;
var mc = new Hammer.Manager(this),
itemLength = $(this).find('li').length,
count = 0,
slide = $(this),
timer;
var sliderWrapper = slide,
slideItems = sliderWrapper.find('li'),
//slider = sliderWrapper.find('li'),
totalPanels = slideItems.length,
currentSlide = parseInt(sliderWrapper.attr('data-slide'));
// mc.on("panleft panright", function(ev) {
// direction = ev.type;
// });
mc.add(new Hammer.Pan({
threshold: 0,
pointers: 0
}))
mc.on('pan', function(e) {
var percentage = 100 / totalPanels * e.deltaX / window.innerWidth;
var transformPercentage = percentage - 100 / totalPanels * activeSlide;
touchSlider.style.transform = 'translateX( ' + transformPercentage + '% )';
var sliderWrapper = $(e.target).closest('.faculty-carousel')
if (e.isFinal) { // NEW: this only runs on event end
var newSlide = activeSlide;
if (percentage < 0)
newSlide = activeSlide + 1;
else if (percentage > 0)
newSlide = activeSlide - 1;
goToSlide(newSlide, sliderWrapper);
}
});
var goToSlide = function(number, sliderWrapper) {
if (number < 0)
activeSlide = 0;
else if (number > totalPanels - 1)
activeSlide = totalPanels - 1
else
activeSlide = number;
sliderWrapper.attr('data-slide', activeSlide);
touchSlider.classList.add('slide-animation');
var percentage = -(100 / totalPanels) * activeSlide;
touchSlider.style.transform = 'translateX( ' + percentage + '% )';
timer = setTimeout(function() {
touchSlider.classList.remove('slide-animation');
}, 400);
};
});
}
$(document).ready(function() {
fCarousel();
})
$(window).on('resize', function(){
fCarousel();
})
Код: Выделить всё
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
.faculty-items li {
height : 100px;
}
.faculty-items li:nth-child(odd) {
background-color : grey;
}
.faculty-items li:nth-child(even) {
background-color : aqua
}
.faculty-items {
overflow : hidden;
position : relative;
right : 0;
display : flex;
-webkit-transition: transform 0.3s linear;
}
.faculty-carousel .controls {
display : block;
}
Код: Выделить всё
Carousel
[*]
[list]
Item 1
[*]Item 2
[*]Item 3
[*]Item 4
[*]Item 5
[*]Item 6
[/list]
prev
next
[list]
[*]Item 1
[*]Item 2
[*]Item 3
[*]Item 4
[*]Item 5
[*]Item 6
[/list]
prev
next
[list]
[*]Item 1
[*]Item 2
[*]Item 3
[*]Item 4
[*]Item 5
[*]Item 6
[/list]
prev
next
Подробнее здесь:
https://stackoverflow.com/questions/459 ... controls-n
1735272479
Anonymous
Я только что закончил создание карусели, над которой работал, которая использует пролистывание/касание, а также такие элементы управления, как предыдущая/следующая, для управления каруселью. Прямо сейчас у меня возникла проблема, связанная с поведением карусели. По сути, я пытаюсь заставить его скользить один за другим. Вот пример кода, над которым я работал. Сейчас кажется, что он скользит на 2 или 3 в зависимости от того, сколько каруселей я разместил. У меня также возникла проблема с тем, чтобы сделать его отзывчивым. [code]function fCarousel() { // var activeSlide = 0; // $('.faculty-carousel').attr('data-slide', '0'); var viewPortSize = $(window).width(), facultyPanel = $('.faculty-carousel .faculty-items li'), profileCount = facultyPanel.length, activeSlide = 0, carousel = $('.faculty-carousel .faculty-items'); $('.faculty-carousel').attr('data-slide', '0'); //Set Panel Size based on viewport if (viewPortSize 0) { // Decremement current slide currentSlide--; // Assign CSS position to clicked slider var transformPercentage = -1 * currentSlide / facultyProfileCount * 100; carousel.css('transform', 'translateX(' + transformPercentage + '% )'); // Update data-slide attribute carouselWrapper.attr('data-slide', currentSlide); activeSlide = currentSlide; } }); $('.next').on('click', function(e) { event.stopPropagation(); // store variable relevent to clicked slider var carouselWrapper = $(this).closest('.faculty-carousel'), facultyProfilePanel = carouselWrapper.find('.faculty-items li'), facultyProfileCount = facultyProfilePanel.length, viewPortSize = $(window).width(), carousel = carouselWrapper.find('.faculty-items'), position = 0, currentSlide = parseInt(carouselWrapper.attr('data-slide')); // Check if dataslide is less than the total slides if (currentSlide < facultyProfileCount - 1) { // Increment current slide currentSlide++; // Assign CSS position to clicked slider var transformPercentage = -1 * currentSlide / facultyProfileCount * 100; carousel.css('transform', 'translateX(' + transformPercentage + '% )'); // Update data-slide attribute carouselWrapper.attr('data-slide', currentSlide); activeSlide = currentSlide; } }) $('.faculty-carousel .faculty-items').each(function() { // create a simple instance // by default, it only adds horizontal recognizers var direction; var touchSlider = this; var mc = new Hammer.Manager(this), itemLength = $(this).find('li').length, count = 0, slide = $(this), timer; var sliderWrapper = slide, slideItems = sliderWrapper.find('li'), //slider = sliderWrapper.find('li'), totalPanels = slideItems.length, currentSlide = parseInt(sliderWrapper.attr('data-slide')); // mc.on("panleft panright", function(ev) { // direction = ev.type; // }); mc.add(new Hammer.Pan({ threshold: 0, pointers: 0 })) mc.on('pan', function(e) { var percentage = 100 / totalPanels * e.deltaX / window.innerWidth; var transformPercentage = percentage - 100 / totalPanels * activeSlide; touchSlider.style.transform = 'translateX( ' + transformPercentage + '% )'; var sliderWrapper = $(e.target).closest('.faculty-carousel') if (e.isFinal) { // NEW: this only runs on event end var newSlide = activeSlide; if (percentage < 0) newSlide = activeSlide + 1; else if (percentage > 0) newSlide = activeSlide - 1; goToSlide(newSlide, sliderWrapper); } }); var goToSlide = function(number, sliderWrapper) { if (number < 0) activeSlide = 0; else if (number > totalPanels - 1) activeSlide = totalPanels - 1 else activeSlide = number; sliderWrapper.attr('data-slide', activeSlide); touchSlider.classList.add('slide-animation'); var percentage = -(100 / totalPanels) * activeSlide; touchSlider.style.transform = 'translateX( ' + percentage + '% )'; timer = setTimeout(function() { touchSlider.classList.remove('slide-animation'); }, 400); }; }); } $(document).ready(function() { fCarousel(); }) $(window).on('resize', function(){ fCarousel(); })[/code] [code]/* http://meyerweb.com/eric/tools/css/reset/ v2.0 | 20110126 License: none (public domain) */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } /* HTML5 display-role reset for older browsers */ article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } table { border-collapse: collapse; border-spacing: 0; } .faculty-items li { height : 100px; } .faculty-items li:nth-child(odd) { background-color : grey; } .faculty-items li:nth-child(even) { background-color : aqua } .faculty-items { overflow : hidden; position : relative; right : 0; display : flex; -webkit-transition: transform 0.3s linear; } .faculty-carousel .controls { display : block; }[/code] [code] Carousel [*] [list] Item 1 [*]Item 2 [*]Item 3 [*]Item 4 [*]Item 5 [*]Item 6 [/list] prev next [list] [*]Item 1 [*]Item 2 [*]Item 3 [*]Item 4 [*]Item 5 [*]Item 6 [/list] prev next [list] [*]Item 1 [*]Item 2 [*]Item 3 [*]Item 4 [*]Item 5 [*]Item 6 [/list] prev next [/code] Подробнее здесь: [url]https://stackoverflow.com/questions/45982800/carousel-slides-incorrectly-when-swiping-or-when-clicking-the-slider-controls-n[/url]