Owl carousel autowidth не работает

Содержание
  1. Center option with auto width — can’t scroll/swipe to end of carousel — last items not visible #1999
  2. Comments
  3. pixelvicky commented Aug 8, 2017
  4. Wrong owl-stage width calculation when using «autoWidth: true» #1139
  5. Comments
  6. danielepennati commented Nov 25, 2015
  7. kevindeasis commented Jan 7, 2016
  8. imolorhe commented Jan 21, 2016
  9. danielepennati commented Jan 22, 2016
  10. Jehu commented Jun 16, 2016
  11. pascalporedda commented Jun 18, 2016
  12. pablo-sg-pacheco commented Jul 6, 2016 •
  13. pablo-sg-pacheco commented Jul 7, 2016
  14. pablo-sg-pacheco commented Jul 7, 2016
  15. kampiamodikuesto commented Mar 28, 2017
  16. kampiamodikuesto commented Mar 29, 2017 •
  17. masbug commented Apr 23, 2017
  18. akash-d commented Jun 5, 2017
  19. kwentworth commented Jun 15, 2017
  20. tonxxx commented Jun 22, 2017
  21. quinnvaughn commented Aug 15, 2017
  22. quinnvaughn commented Aug 15, 2017
  23. adigourdi commented Aug 28, 2017 •
  24. jim22 commented Sep 13, 2017
  25. sasha1344 commented Oct 29, 2017
  26. EdenK commented Nov 19, 2017
  27. murph133 commented Feb 22, 2018 •
  28. folkevil commented May 8, 2018
  29. webblufter commented Dec 30, 2018
  30. fitnycdigitalinitiatives commented Mar 28, 2019
  31. oliveratgithub commented Apr 12, 2019
  32. choogoor commented Jun 1, 2019
  33. Kayanski commented Jun 27, 2019
  34. GTCrais commented Aug 10, 2019
  35. sasikasp commented Oct 24, 2019
  36. forwells commented Dec 6, 2019
  37. mrsoftware commented Dec 14, 2019 •
  38. sabat24 commented Dec 19, 2020 •
  39. #длясамыхмаленьких — Установка и настройка слайдера Owl Carousel 2 на сайт
  40. Установка Owl Carousel 2
  41. Подключаем
  42. Используем
  43. Настраиваем и расширяем функционал
  44. Документация по API Owl Carousel 2 на русском
Читайте также:  Не работают туманки ваз 2114 причины

Center option with auto width — can’t scroll/swipe to end of carousel — last items not visible #1999

Comments

pixelvicky commented Aug 8, 2017

I am building a site which uses OwlCarousel and the design behaviour has to be:

  • On load, first image is fully visible, second image is partially visible, and then swipe through.

  • On load the left margin has to be clear white, and as you swipe, the images push into the left margin

However when setting up the Carousel as follows:

You cannot physically swipe all the way across, you get to the 3rd to last item and the carousel will not let you swipe across to the end.

It looks as though the width calculation perhaps doesn’t take into account the initial left offset maybe? As the total calculated with of the carousel items with margins is correct.

It will work fine with center: false OR center: true and autoWidth: false but then this breaks the desired design (which I have to make happen regardless. )

I have tried both OwlCarousel 2.2.1 and 2.3.0 beta.

I note the demo with centring works so a bit confused! Maybe that’s because the demo is entirely same sized items?

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

Источник

Wrong owl-stage width calculation when using «autoWidth: true» #1139

Comments

danielepennati commented Nov 25, 2015

Hello,
I have a strange bug. I have several pages with a carousel with same option

On same of this pages the carousel doesn’t work correctly: the width of the owl-stage element is calculated wrongly and the last item of the carousel goes on a new line (under the firs item in chrome ora under the last item of the first row in firefox). for example look at this page:
http://www.galleriacarlasozzani.org/en/past?milano/2010

the main issue is that it is random. on the vast majority of page everything work fine and the pages with the bug are have exactly the same layout and template of the other one.

Do you have any idea about fixing this?

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

kevindeasis commented Jan 7, 2016

I had the same problem too with older versions of android. The only way I could support it in older versions of anrdroid was to use the older version of carousel or remove autoWidth in owl carousel 2.

imolorhe commented Jan 21, 2016

Any fix for this issue yet? Still bugging me.

danielepennati commented Jan 22, 2016

I’ve fixed it using a simple workaround:

I call a function on the owl events «onInitialized», «onRefreshed». The function simply recalculates the .owl-stage width:

Jehu commented Jun 16, 2016

why is this closed?

pascalporedda commented Jun 18, 2016

This issue should be fixed in the version 2.1.6. If you experience any unwanted behaviour, feel free to report it via an issue.

pablo-sg-pacheco commented Jul 6, 2016 •

Version 2.1.6 fixed this issue for me. Thanks

pablo-sg-pacheco commented Jul 7, 2016

Actually it is still weird.
Sometime it works. Sometimes not.

The last item is still going in a new line some times. But even when the last item goes on the right place i can’t move to last item

pablo-sg-pacheco commented Jul 7, 2016

I think I fixed it loading the carousel on window.load, instead of document ready and adding a last fake item on html

kampiamodikuesto commented Mar 28, 2017

thanks i fix this problem adding this lines of code

kampiamodikuesto commented Mar 29, 2017 •

precendent fix don’t work for me, i have to add 1 to this code

The problem i think is that coordinates function calculate ceil on negative value (es -37.5 —> -37) Css width for owl-stage is taken by last coordinates that is 1px short (es. 37 and not 38)
this isn’t a problem to first load but it is a problem when resize.

masbug commented Apr 23, 2017

I can confirm that this is still a problem in version 2.2.1 (using autoWidth=true). If I change width on owl-stage just by adding 1px then the issue is resolved.

Another solution that worked for me is setting box display on owl-stage:
.owl-stage <
display: -webkit-box;
display: -moz-box;
display: -ms-box;
display: box;
>

akash-d commented Jun 5, 2017

@masbug Thanks alot! It works perfectly fine now.

kwentworth commented Jun 15, 2017

what worked for me was adding a rule for
.owl-item <
display: inline !important;
>

tonxxx commented Jun 22, 2017

@masbug thanks. works well for me.. spent a lot of time finding workaround and finally it’s fxed ))

quinnvaughn commented Aug 15, 2017

@masbug It should be display: flex;, but it still doesn’t work for me every time. I have to reload. Before I do, all the items are scrunched up.

quinnvaughn commented Aug 15, 2017

Also @masbug that does seem to work, but not with center: true, as it throws the alignment of the slides off.

adigourdi commented Aug 28, 2017 •

I’ve encountered this issue this morning
It seems to happen only when there is an item that is larger than stageOuter’s width, appending the difference between these items to the width of the stage solves the problem
I’ve written this code to test my theory

The 1.2 factor is there to assure the width isn’t still short, it needs to be 1 or higher, putting 0.9 will make the second line appear again

The solution I applied is triggering a refresh on the carousel right after initialisation, resizing the window recalculates the stage width correctly

I tried multiple events: resize.owl.carousel , resized.owl.carousel , and refreshed.owl.carousel , none of them solved the issue

Edit: tested with current release 2.2.1

jim22 commented Sep 13, 2017

@adigourdi — Thanks. Triggering a refresh after initialization worked for me as well.
$(‘.slideshow-images’).owlCarousel(< autoWidth: true, . >).trigger(‘refresh.owl.carousel’);

sasha1344 commented Oct 29, 2017

Hi. I had the same problem. The script didn’t understand stage width, because images haven’t been uploaded. To solve this problem I used jQuery plugin «Images Loaded» ( https://github.com/desandro/imagesloaded )

I hope this helps someone)

EdenK commented Nov 19, 2017

@adigourdi — Thanks this worked for me as well.
$(‘.owl-carousel’).owlCarousel(< autoWidth: true >).trigger(‘refresh.owl.carousel’);

murph133 commented Feb 22, 2018 •

A simple solution. Double the preset .owl-stage width:

folkevil commented May 8, 2018

I got same problem today,
@sasha1344 your solution worked for me. But we can fix by css with:

.owl-stage <
display: -webkit-box;
display: -moz-box;
display: -ms-box;
display: box;
>
.owl-carousel

webblufter commented Dec 30, 2018

Same issue solved by ‘onInitialized’ and ‘onRefreshed’ my code is below
jQuery(‘.owl-carousel’).owlCarousel( <
dots: false,
loop:false,
nav: false,
autoWidth: true,
scrollbarType: «progress»,
onInitialized: function()< stage = jQuery('.owl-stage'); stage.width(stage.width() * 2); >,
onRefreshed: function()< stage = jQuery('.owl-stage'); stage.width(stage.width() * 2); >,
>);

fitnycdigitalinitiatives commented Mar 28, 2019

I ran into this same problem and I think it’s related to #604. It’s not strictly limited to google fonts—any loaded font causes this problem. What happens is that it calculates the owl-stage based on a generic font and then once your font is loaded it causes the stage to be too small (because whatever font you are using causes your element to be a little bigger). A true fix would recalculate the stage whenever there’s a change in the item size. I think just doubling the stage width size does the trick, but one could also use something like this which can trigger once a font is loaded and then trigger a refresh on the owl.

oliveratgithub commented Apr 12, 2019

For me, the only solution that worked was the one with adding CSS-styles for box-styles as provided by @masbug – triggering a «refresh.owl.carousel» or something with «onInitialized» / «onRefreshed» didn’t work.

choogoor commented Jun 1, 2019

Hi all, it doesn’t work well for neither solutions display: box or triggering refresh. With triggering refresh it works on firefox but on chrome problem is still there. Using display: box on .owl-stage calculate height correctly but center option then doesn’t work well.

Kayanski commented Jun 27, 2019

@choogoor the fix by kampiamodikuesto (the 1 + Math.ceil in owl.carousel.js ) fix worked nice for me

GTCrais commented Aug 10, 2019

None of these solutions worked for me. The only thing that worked for me is adding coordinate—; as the first line of Owl.prototype.animate function on line 938, making it:

sasikasp commented Oct 24, 2019

all the above solutions did not work for me, so I did it myself by using CSS

this is what i did.

.owl-carousel .owl-stage <
display: flex;
>

.owl-item <
width: max-content !important;
>

.item <
width: max-content;
>

.owl-carousel .owl-item img <
width: auto;
max-height: 460px;
margin-left: auto;
margin-right: auto;
>

This works for me, hope it helps someone too.

forwells commented Dec 6, 2019

I can confirm that this is still a problem in version 2.2.1 (using autoWidth=true). If I change width on owl-stage just by adding 1px then the issue is resolved.

Another solution that worked for me is setting box display on owl-stage:
.owl-stage <
display: -webkit-box;
display: -moz-box;
display: -ms-box;
display: box;
>

More Thanks, If not work, Please try !important

mrsoftware commented Dec 14, 2019 •

@masbug solution worked for me. thanks.

sabat24 commented Dec 19, 2020 •

The source of the problem is that line:

in Chrome you often get width as 0. I think that author tried to resolve such issues by using an autoRefresh option. However it’s not reliable as you do not know how long does it take to load all images. Solutions with initialized handler may not work, because there may be not enough time to correctly load and recalculate width of all images by browser. Solution with imagesLoaded is better, but still not perfect. Firefox has no problems with it, but Chrome does. Sometimes latest elements with images may still return zero width, because browser wasn’t able to calculate new width of parent elements even if images were loaded. This is why I created my own solution.

It checks if all items return non-zero width and re-run the check if not. If that condition is met, it refreshes the owl object.

It may need some extra work if you use some lazy-loaded items, which should be ignored and so on. There also should be some limit to prevent infinite loop if image wasn’t loaded.

Источник

#длясамыхмаленьких — Установка и настройка слайдера Owl Carousel 2 на сайт

А вот и подоспела очередная рубрика в моем блоге — #длясамыхмаленьких . В ней я буду рассказывать вам о простых вещах из мира веб-разработки доступным языком (попытаюсь во всяком случае). Сегодня мы поговорим о такой банальной вещи как слайдер. Скорее всего на подавляющем количестве сайтов в том или ином виде присутствует этот элемент. Он позволяет запихать большой объем данных в ограниченное по размеру место, да и в целом способов его применения масса.

За свою жизнь я перепробовал кучу всевозможных слайдеров и в качестве основного у меня всегда был «FlexSlider 2» до того момента пока я не попробовал героя нашей сегодняшней записи — Owl Carousel 2.

Owl Carousel 2 — Гибкий, приятный и удобный в использовании слайдер. Он интуитивно понятно себя ведет, адаптивен, замечательно себя чувствует на любых платформах и разрешениях. Использовать его в работе — одно удовольствие.

Собсно для начала нам нужно его скачать. Пакет доступен из npm и bower:

npm npm install —save owl.carousel

bower bower install —save owl.carousel

Если вы не хипстер используете пакетные менеджеры, то можно скачать с гитхаба в разделе релизов: Скачать Owl Carousel 2

На момент написания статьи актуальная версия 2.1.6 и в качестве примера я буду использовать ее.

Само собой нам так же понадобиться jQuery.

Подключаем

Скачав и распаковав Owl Carousel 2 нам нужно его подключить. Для этого в добавляем стили:

Если вам лень писать свои стили для внешнего вида слайдера, то можете подключить CSS файл со стандартной темой от разработчиков.

И внизу страницы подключаем непосредственно саму js’ку. АЛЯРМА! Owl Carousel должен подключаться после jQuery!

Используем

Добавляем в нужное вам место на странице блок со слайдером

Содержимым слайдера может выступать что угодно. Картинки, текст, списки, видео, все на что хватит вашей фантазии, но оно обязательно должно быть обернуто в контейнер (Например

Если вы не используете стандартную тему (owl.theme.default.css) то класс owl-theme добавлять не нужно.

Теперь просто вызываем функцию плагина (добавляем следующий код в конце странице, после подключения owl.carousel.min.js)

Если у вас уже есть вызовы других функций по (document).ready , то можно просто к ним добавить $(‘.owl-carousel’).owlCarousel(); )

Все! Карусель установлена и функционирует. Вы молодец!

Настраиваем и расширяем функционал

У плагина достаточно простое и понятное API с помощью которого можно задавать опции к вызову нашей карусели. Ниже я приведу их подробную таблицу с русским описанием и приложу пример моего использования его на последнем разрабатываемом мной проекте, для наглядности.

Табличка вышла не маленькая и перевод получился немного не полный, но самое важное и постоянно используемое я перевел. Как только у меня будет чуть больше свободного времени я обязательно доведу перевод на русский язык документации по Owl Carousel 2 до конца.

Дабы предупредить некоторые глупые вопросы у людей которые не знают ничего о типах данных — сделаю небольшой дисклеймер. В таблице приведен параметр и тип значения в котором нужно его указывать. Тип Number используется как ни странно для числовых значений, как целых так и дробных (например 1, 5, 80). Тип Boolean является булевым и имеет два значения — true (истина) или false (ложь) (грубо говоря да\нет). String это строчный тип данных, в который вы можете записывать любую строку (оборачивается как в одинарные так и в двойные кавычки). Так же в параметр можно передавать и другие данные, например массивы (Array) или же целые функции.

Параметр Тип Стандартное значение Описание
items Number 3 Кол-во отображаемых элементов в слайдере
margin Number 0 Отступ справа у элементов внутри слайдера (значение в px)
loop Boolean false Бесконечное зацикливание слайдера (для лучшего эффекта продублируйте первый и последний элемент)
center Boolean false Позиционирование элементов по центру (лучше работает при нечетном кол-ве элементов)
mouseDrag Boolean true Перелистывание элементов зажатой мышкой
touchDrag Boolean true Перелистывание касанием (смартфоны\планшеты)
pullDrag Boolean true Stage pull to edge.
freeDrag Boolean false Item pull to edge.
stagePadding Number 0 Padding left and right on stage (can see neighbours).
merge Boolean false Merge items. Looking for data-merge=’’ inside item..
mergeFit Boolean true Fit merged items if screen is smaller than items value.
autoWidth Boolean false Размещение элементов не сеткой (Задайте высоту каждому диву)
startPosition Number/String 0 Стартовая позиция (?) или URL хэш (Например «#id»)
URLhashListener Boolean false Отслеживание изменений URL хэша (Хэш должен присутствовать на каждом элементе)
nav Boolean false Отображение кнопок вперед\назад
navText Array Текст на кнопках навигации. HTML разрешен.
navElement String div Тип DOM элемента для навигационной ссылки в одну сторону.
slideBy Number/String 1 Пролистывание слайдера по оси X. Значение ‘page’ позволяет сделать навигацию по странице.
dots Boolean true Отображение навигационных «точек»
dotsEach Number/Boolean false Отображение навигационных «точек» ‘x’ кол-во элементов
dotData Boolean false Используется data-dot контентом
lazyLoad Boolean false Lazy-Load картинок. data-src и data-src-retina указываются для высоких разрешений. Так же загружает изображение инлайново в свойство background если элемент не является
lazyContent Вырезано из финальной версии, но разработка все еще ведется.
autoplay Boolean false Автоматическое пролистывание
autoplayTimeout Number 5000 Интервалы между пролистыванием элементов
autoplayHoverPause Boolean false Останавливает автопроигрывание если навести мышкой (hover) на элемент
smartSpeed Number 250 Просчитывание скорости (В оф. документации больше информации нет)
fluidSpeed Number
autoplaySpeed Number/Boolean false Скорость автоматического пролистывания
navSpeed Number/Boolean false Скорость навигации
dotsSpeed Number/Boolean Скорость навигации «точками»
dragEndSpeed Number/Boolean false Drag end speed.
callbacks Boolean true Включение\отключение колбэк ивентов.
responsive Object empty object Объект содержит в себе настройки для адаптивности. Если установить значение в false — поддержка адаптивности отключается.
responsiveRefreshRate Number 200 Responsive refresh rate.
responsiveBaseElement DOM element window Вешается на любой DOM элемент. Если вы хотите поддержку старых браузеров (например ie8) вешайте его на главный оберточный элемент (wrapper). Это должно предупредить неадекватный ресайз.
video Boolean false Включение\отключение поддержки в слайдере видео (youtube\vimeo\Vzaar)
videoHeight Number/Boolean false Установка высоты видео
videoWidth Number/Boolean false Установка ширины видео
animateOut String/Boolean false CSS класс анимации «out»
animateInClass String/Boolean false CSS класс анимации «in»
fallbackEasing String swing Смягчение (?) CSS2 $.animate.
info Function false Колбэк для извлечение базовой информации (текущий элемент/страницы/ширины).
nestedItemSelector String/Class false Используйте если элемент слайдера глубоко вложен в генерируемый контент, например ‘myitem’. Не используйте точку перед названием класса.
itemElement String div Тип DOM элемента слайдера.
stageElement String div Тип DOM элемента owl-stage.
navContainer String/Class/ID/Boolean false Установка своего контейнера для навигации
dotsContainer String/Class/ID/Boolean false Установка своего контейнера для навигации по «точкам»

Вот пример моего вызова Owl Carousel 2 с комментариями:

Чтобы сделать два или несколько слайдеров на сайте с помощью Owl Carousel 2 достаточно просто вызывать функцию не по классу а по id (как в моем примере), и не забудьте их расставить непосредственно в разметке страницы.

На этом собственно все, если у вас останутся какие-то вопросы — задавайте их в комментариях. Удачи!

Источник

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