Swiper не работает activeindex

[BUG] Freemode breaks swiper responsive #2708

Comments

Tucsky commented Jul 9, 2018 •

This is a (multiple allowed):

Swiper Version: 4.3.3

Platform/Target and Browser Versions: Chrome Win

Live Link or JSFiddle/Codepen or website with isssue: https://jsfiddle.net/Tucsky/0jLz2dkc/

What you did

Setup a classic swiper
Enable freemode with sticky (important)
Try resize the swiper container

Expected Behavior

Each slide width & wrapper translate3d updating accordingly to the container width = responsive OK

Actual Behavior

Slides width updating but wrapper translate is NOT => responsive KO

The text was updated successfully, but these errors were encountered:

Tucsky commented Aug 7, 2018 •

One way to solve that using a very DIRTY workaround is to listen browser resize, quicly disable freemode, and re-enable it after resize is done (cleartimeout timeout .5s inside in the resize handler).

stale bot commented Nov 20, 2018

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Tucsky commented Nov 20, 2018

Hi @nolimits4web,
Any reason behind this wontfix tag? I explained everything about that issue and no answer 🙁

stale bot commented May 19, 2019

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

justingrant commented Aug 6, 2019 •

@Tucsky — a cleaner workaround is probably to put this in your resize handler:

This will simply scroll the slider to the current slide. Note that with this solution, there’s no need to remove/re-add freeMode or freeModeSticky. Also, because there’s no setTimeout, there’s no delay before the proper slide is shown after a resize.

Note that this workaround only fixes the problem where the slides aren’t sticky after a resize. It won’t help the other problem which is that resizing will change the active index.

I certainly agree that this seems like a bug. Resizing the container should keep the current active index unchanged and (if sticky) should ensure that slides are stuck to the edges after resize.

BTW, here’s a simple codepen that illustrates the problem in under 30 lines of HTML+CSS+JS: https://codepen.io/justingrant/pen/wVpeda. If you resize the browser horizontally, then the active index will change, which is unexpected. Note that setting sticky is not required for it to repro; any freemode+virtual swiper instance will exhibit the problem.

Any reason behind this wontfix tag?

It looks like wontfix is automatically added by the stale bot, under the assumption that stale issues with no activity won’t be fixed. If you add a comment, stalebot will remove the label. EDIT: me adding a comment didn’t remove the wontfix label. Not sure why, given that it was removed after your Nov 20, 2018 comment.

justingrant commented Aug 7, 2019

BTW, I’m about to start work on a PR to fix this issue. At this point in my investigation, it looks like the culprit is here:

Lines 20 to 40 in d00106c

swiper . updateSize ( ) ;
swiper . updateSlides ( ) ;
if ( params . freeMode ) <
const newTranslate = Math . min ( Math . max ( swiper . translate , swiper . maxTranslate ( ) ) , swiper . minTranslate ( ) ) ;
swiper . setTranslate ( newTranslate ) ;
swiper . updateActiveIndex ( ) ;
swiper . updateSlidesClasses ( ) ;
if ( params . autoHeight ) <
swiper . updateAutoHeight ( ) ;
>
> else <
swiper . updateSlidesClasses ( ) ;
if ( ( params . slidesPerView === ‘auto’ || params . slidesPerView > 1 ) && swiper . isEnd && ! swiper . params . centeredSlides ) <
swiper . slideTo ( swiper . slides . length — 1 , 0 , false , true ) ;
> else <
swiper . slideTo ( swiper . activeIndex , 0 , false , true ) ;
>
>
Читайте также:  Не работает звонок дискорд

If I’m understanding this code correctly, here’s what this code does when a resize happens:

  1. the new size of the container is calculated in swiper.updateSize() .
  2. then swiper.updateSlides(); creates an array of the starting pixel offset of each slide, using the container size calculated in (1).
  3. if freeMode is active, then the old (pre-resize) swiper.translate value is retained (unless the old translate value is now out of bounds, which seems to be unusual unless the active index is already near the beginning or end).
  4. finally swiper.updateActiveIndex() calculates the new active index seeing which slide contains the translate value, using the new sizes from (2).

The problem, unless I’m missing something, is that the old translate value (3) is used to find a match in the new slide offsets (2). This obviously breaks.

The fix instead is to do something more similar to what the non- freeMode implementation does, which is to set the new translate value based on the current active index. The main potential issue that I see is how to handle the case where the slide was not snapped to the edge before the resize. The simplest solution (which is what I’m planning to implement in a PR) is simply to do what the non- freeMode solution does: call slideTo to snap the current index to the new, post-resize layout.

In theory there could be a more sophisticated solution which could try to retain the offset of the current slide relative to the bounds of the container, but there are so many corner cases with that solution (e.g. what if the offset is larger than the container? what about centered slides? what about RTL? etc.) that I don’t think it’s worth pursuing.

Anyway, that’s what I’m thinking of implementing in a PR. Planning to start on it tomorrow morning.

@nolimits4web, @Tucsky — if you have any concerns or suggestions about this proposed solution, please let me know.

Источник

iDangero.us Swiper slide count when loop is true

I’m using iDangero.us Swiper js for a webpage, and initialization code is as following:

And I need to get current slider index and total count of sliders. Swiper API provides mySwiper.activeIndex property and mySwiper.slides but the problem is that when loop is true they don’t give correct index and count.

Is there any way to get these numbers correctly when loop is true?

8 Answers 8

The number of slides, and thus sometimes the activeIndex , is «wrong» by design when loops are involved: https://github.com/nolimits4web/Swiper/issues/1205

Best way I could find to get the total number of slides is:

You could use that to get the current index (this one is zero-based):

This is not ideal, of course. You could open a GitHub issue and propose adding more convenient ways of accessing these values.

As of May 2016 they have added the realIndex property!

Things to be aware of: 1.) the realIndex property is returned as a string instead of an integer (just in case you need to do math with it) 2.) the realIndex property starts with 0(as it should), unlike activeIndex in loop mode which in my case started with 1

Just adding yet another answer, since Swiper hasn’t included the realIndex property yet. Here is a nice little way of getting the real index when looping, without subtracting a hard coded number (which might easily change).

this work in both modes, loop or not

also, the number of total slides in both modes:

Although this question has been answered already, I thought I’d add my working code based off the accepted answer.

Main issue I had with a looping gallery, is if you go back from the first slide, the current slide reads as 0. Possibly because it’s a clone?

Anyway, here’s a stripped-back (slightly untested) working solution:

Use the above to display current and total slides on your page. Obviously adjust the ID’s in your HTML accordingly.

Читайте также:  Как починить подогрев сидений калина

I would think this value of the actual index value should be available in the Swiper API, although it’s nowhere to be found, so for now you’ll have to roll your own function to get that value.

This function (tested and works) was provided to me in this thread on the Swiper GitHub Issues page: Need a way to get the accurate activeIndex in loop mode

In loop mode active index value will be always shifted on a number of looped/duplicated slides. you can get attribute ‘data-swiper-slide-index’ with a function like:

Источник

проблема с опасным swiper с динамическим контентом

Я применяю плагин idangerous swiper для прокрутки контейнера, содержимое которого динамически загружается с помощью ajax, я инициализирую плагин после вызова ajax, проблема в том, что прокрутка не работает, пока я не изменю размер браузера. Я протестировал его со статическим контентом, он работает нормально, нет необходимости изменять размер окна, но как только я переключаюсь на динамический контент, прокрутка не работает, пока я не изменяю размер браузера.

Вот как я инициализирую плагин

Высота контейнера-шпинделя составляет 100%

7 ответов

Я нашел решение, я добавил эту функцию, которую я вызываю после первой инициализации плагина

Это исправление было упомянуто в другом плагине, и когда я попробовал его с этим плагином, это сработало. Это связано с тем, что плагин не знает об изменениях, произошедших в DOM.

У меня есть решение без JS.

HTML

CSS

Следовательно, этот метод также будет работать для создания любого размера div так, как это делает изображение. Масштабирование его высоты с фиксированным соотношением сторон по ширине.

Волшебство заключается в том, что браузеры обрабатывают значения margin / padding% как процент от ширины элемента, даже если вы дополняете верх или низ указанного элемента.

Надеюсь это поможет!

Я просто хотел добавить, что у меня также были проблемы с настройкой Swiper для работы с динамически загружаемым контентом через ajax . Это совершенно очевидно, потому что контент еще не был загружен, когда был запущен Swiper. Я решил это, используя собственную функцию добавления Swiper вместо моей собственной. Это было в версии 3.3.1, и это исправило это для меня без необходимости использовать setTimeout() или что-то еще!

Я надеюсь, что это помогает некоторым нуждающимся людям!

Для адаптивного дизайна я вызываю следующий метод resizeFix

Обновлено для Изменения в документации Swiper, так как .reInit больше не является функцией.

Мое исправление для Swiper 3.x (я полагаю, что вышеперечисленные обложки 2.x)

Источник

Как вызвать событие в swiper по нажатию на кнопку?

Есть такая конструкция слайдера:

Вся проблема заключается в том, что при нажатии на кнопки «Все/Последние» нужно что-бы вложенный слайдер переключался на первый слайд. Я попытался использовать метод swiper.slideto из документации, выглядит это так:

но судя по всему слушается он только внутри самого const Swiper , только вот функцию туда вложить не получается. Так же у Swiper есть событие click, которое можно обрабатывать, но дело в том, что слушает он сам клик по слайдеру, а не по pagination(Кнопки переключения).

1 ответ 1

Учитывая, что в вашем коде вложенные слайдеры привязаны к одному и тому instance — управлять ими будет невозможно. Одно из решений этой проблемы:

Создаем переменную, где будем хранить instance для каждого вложенного слайдера, допустим:

и, чтобы одной навигацией управлять разными вложенными слайдерами, создаем переменную, где будем хранить индекс текущего(видимого в настоящий момент) вложенного слайдера:

создаем функцию, которая будет создавать вложенные слайдеры по требованию

Создаем функцию, которая будет проводить управление активным вложенным слайдером посредствам пользовательской навигации:

И используя метод on создаем функционал, который будет создавать вложенные слайдеры и управлять индексом активного слайдера:

Добавляем к элементам навигации обработчики событий:

Слайдер готов к работе. В качестве наглядного пример — привожу рабочий пример:

Источник

Infinite loop with slidesPerView: auto, loopFix() issues #2942

Comments

nadamai commented Jan 10, 2019 •

This is a (multiple allowed):

Swiper Version: 4.4.6 (also tested 4.4.x versions and the problem persists)

Platform/Target and Browser Versions: all platforms and browsers I’ve been testing: Windows/Android and Chrome/Opera/Firefox (the most actual versions)

What I did

I use swiper with the following settings (the «big case»):

Читайте также:  За какое время должны отремонтировать автомобиль осаго

+some css styles (I did put them in codepens). After some experiments I’ve managed to recreate the issue only with these settings (the «small case»):

I don’t know if solving problem for the «small case» will be sufficient for solving the «big case», but for sure it’s a good way to start.

Behavior

If I slide to the left, everything seems fine (unless the screen is very big or there are too few slides, i.e. 2), but when I swipe to the right, duplicated elements won’t show up on the right side of the slider, which causes a huge empty space after the slides. It’s even worse if I swipe very fast (it may cause the whole container to be empty for a moment). Occasionally the slider updates and the duplicates «jump in» to the right place, but it’s too soon, so it looks bad and may be confusing for the user.

I could find some similar issues here on GitHub, but none of the presented fixes worked for me. For instance I’ve been playing with loopedSlides and loopAdditionalSlides options (i.e. I’ve been trying to put there some huge values like slidesNum , 2 * slidesNum , 10 * slidesNum , 50 or slidesNum — 1 , where slidesNum contains the initial slides number). It didn’t help.

Moreover I’ve got impression that changing loopAdditionalSlides value option is doing literally nothing. In the docs it’s said that it’s the «number of slides that will be cloned after creating of loop», but as far as I could see, number of cloned slides is always equal to the number of original slides — please correct me if I’m wrong. So technically, how does this option work?

The other thing I’ve tried was translating the slider manually when the very last slide appears on the screen, but then I had problems with smooth movement/free mode momentum (see «Big case»).

Attemption to fix this

I’ve been trying to modify swiper.js script in order to make it work. First of all I’ve noticed that the method loopFix is responsible for «fixing» the loop (to be more specific it handles the translation of slider if some conditions are met). These conditions look like this:

First of all I replaced the 2 multiplier in the second condition with 1 (to tell the truth I couldn’t understand why the 2 is there, as activeIndex >= loopedSlides is the opposite condition to the activeIndex ). Can some good soul explain me why there is 2 ? Thanks!

Secondly I used the console.log and observed that the first condition for negative oversliding was sometimes fulfilled even though I was swiping to the positive direction, so I decided to fix this by imposing some additional condition here related to the sliding direction. So I got something like this:

In general this fix may not be sufficient for some RTL settings, but it helped a little bit in my case. Here is an example: «attemption to fix» codepen.

As you can see it may seem to work now, but there are still some problems:

  • variable dir has got wrong value after first swipe in the opposite direction (for example if we are swiping left and then we swipe right for once, the dir variable still evaluates to ‘left’ not to ‘right’; it’ll have the correct value ‘right’ only if we swipe right for the second time and further). So the problem still may occur in these kinds of situations.
  • fast swiping can still cause swiper container to be partially empty; in the worst scenario I could limit the maximum slider speed, but it’s not very user friendly
  • (hard to reproduce) I’m not sure if it concerns the small case, but for the big case in Opera and Chrome browsers some random swiping may cause an infinite script loop (more precisely the method swiper.loopFix(); in line 3038 of the swiper.js (ver. 4.4.6) starts to run infinitely, causing the whole slider to freeze).

The text was updated successfully, but these errors were encountered:

Источник

Оцените статью