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

autoHeight breaks on Safari #556

Comments

ndimatteo commented Oct 14, 2014

When OwlCarousel initializes on safari the height is set to 1px for some reason. This seems to only affect carousels with the ‘autoHeight’ plugin being used. The only way to jig it properly is either going to a new slide (recalculates height properly) or refreshing the page (works sometimes).

This only happens in safari (both desktop & mobile iOS)

and here’s a screenshot:

ERROR CORRECT

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

ndimatteo commented Oct 16, 2014

Until they release a fix for this, if anyone’s looking for a quick solution, I added this to force it to recalculate:

unostella commented Oct 21, 2014

Hi @ndimatteo, I tried to use this fix but the problem was still there.
The way around it is to enforce refresh with autoPlay or what worked for me, triggering owl within window load, that’s also nested in document ready.

joeyjoejoejr commented Feb 13, 2015

Can someone verify that this is still an issue?

seamofreality commented Apr 28, 2015

Yes, currently working on a project where this is still an issue.
Our temporary fix is to wait until the carousel images are loaded and init it then so the size is calculated correctly.

lolsps commented Jun 30, 2015

Still an issue. I decided to avoid this option and make images the same.

fulopattila122 commented Jul 9, 2015

As of today it’s still an issue and neither @ndimatteo’s nor @unostella’s workaround did not work for me. In case of the latter it says Uncaught ReferenceError: owl is not defined . Removing the autoHeight option did help.

subduer commented Dec 5, 2016

Hi! I have same problem: Uncaught ReferenceError: owl is not defined.
It appear only once, after web browser starts. Refresh web or navigate somewhere on web makes my OWL working.
None of these workarounds works 🙁 Any ideas? Any other workarounds?

Haprog commented Nov 30, 2017

This issue still seems to persist but also affects Chrome and other browsers.

And I’m pretty sure these issues are all duplicates of this one: #760, #835, #1381, #2039, #2054, #2113.

I’m dynamically creating and initialising the carousel after page has been loaded (window load event has been executed already) and had to figure out a workaround for this problem. This is what I came up with:

Just add this onload handler to each in the carousel:

This seems to work nicely. It will trigger a refresh of the carousel every time an image in the carousel has loaded if the carousel’s auto height wrapper’s height is still 1px (initial size).

First I tried a simpler approach of always just triggering the refresh on image load event but that seemed to cause an infinite loop of triggering the load events and carousel refreshes and the browser would cause constant high CPU usage when the page is open. So this is why I had to add the check to only refresh if the height hasn’t been set yet.

Haprog commented Nov 30, 2017

Actually my workaround above doesn’t seem to be foolproof. It is better than nothing, but still in some cases it seems to not set the height. When I was testing in our project without the fix above I rarely saw the height problem normally, but I could consistently reproduce it when using Chrome’s network throttling set to Fast 3G. With the above fix it seems to work ok on Fast 3G, but still fails to set the height on Slow 3G throttling.

robertrhu commented Jan 15, 2018 •

I was having this issue due to slow site load. Came up with the following solution. See the linked thread.
#2185

Источник

Chrome and autoHeight shows 1px height image when refresh page #538

Comments

jdmoliner commented Oct 3, 2014

When I’m using chrome and refresh the page, the image is only 1px height.

You can check the bug here. Only when refresh the page and chrome:

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

leandroruel commented Oct 8, 2014

it’s working now, close the issue

jdmoliner commented Oct 8, 2014

The bug is still.
Now it is working but with a css trick:

joeyjoejoejr commented Feb 13, 2015

Can someone verify that this is still an issue?

KennethAshley commented Jun 19, 2015

Please upgrade to the newest version of Owl Carousel, released today, and re-open this issue if it persists.

rodrigoAbril commented Aug 18, 2015

I can still replicate this issue when calling from document.ready, if the call is made with window.load everything works.

greg5green commented Aug 18, 2015

You need to use $(window).load instead of $(document).ready if you want to use autoHeight with images. ready fires before images are loaded, so autoHeight is working as it should by setting the height to be 0 or 1 pixels tall. Another option would be to set up the carousel on ready , but trigger a refresh.owl.carousel on load so that the carousel knows to re-check the element’s height.

dallanlee commented Apr 28, 2016

This thread seems a little divided. Can anyone confirm that using $(window).load is the proper/best way to initiate the the owl slider with images and autoHeight? The autoHeight demo uses

Источник

Auto height not working #835

Comments

vdecree commented May 14, 2015

I’ve never needed it before, but I’m trying to get that autoHeight working and it’s not playing ball. I’m using version 2.0.0.

The stage is just keeping a fixed height, despite having 5 slides with different heights of content.

My script is simply:

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

betagoo commented May 19, 2015

I have similar problem with autoHeight=true.
When slides are images, after page load slider height is set to 20px. I have to refresh page, then works fine.
But if browser cache is empty, autoHeight works wrong.
When I set autoHeight: false, everything works fine, but slider height is constant.

mikehdt commented Jun 25, 2015

From http://www.owlcarousel.owlgraphic.com/demos/autoheight.html
«The plan is to calculate all visible items and change height according to heighest item.»

From what I understand, this functionality is not yet currently implemented.

bgonz commented Jun 25, 2015

So is that the case — «autoHeight» is not quite ready yet?

austinhinderer commented Jul 10, 2015

According to the changelog, autoHeight has been fixed. Is this issue resolved?
http://owlcarousel.owlgraphic.com/docs/support-changelog.html

mikehdt commented Jul 13, 2015

That’s the docs for beta 2.4, which are outdated. The owner of the project has changed from OwlFonk to Smashing Boxes. As far as I’m aware does not have this functionality for multiple slides, only for single slides. There is a pre-beta-3 floating around however I’ve not had a chance to test it to see if this has works yet or not.

rezelute commented Jul 17, 2015

The autoHeight is buggy even when using single slides.
The autoHeight function seems to work with changed events but not with resized events. To overcome this i am having to change the stage height every time the browser is resized but then also on the changed events (When you resize the window and then navigate slides, bugs start to show).

owl.on(‘resized.owl.carousel’, function (event) <
setOwlHeight();
>)

owl.on(‘translated.owl.carousel’, function (event) <
//.
setOwlHeight();
>)

kashburn commented Aug 20, 2015

To fix the AutoHeight issue of not resizing on mobile orientation change I changed the /** All event handlers / section of the AutoHeight plugin to read:
/

* All event handlers.
* @Protected
* @type
*/
this._handlers = <
‘initialized.owl.carousel’: $.proxy(function() <
if (this._core.settings.autoHeight) <
this.update();
>
>, this),
‘resized.owl.carousel’: $.proxy(function() <
if (this._core.settings.autoHeight) <
this.update();
>
>, this),
‘changed.owl.carousel’: $.proxy(function(e) <
if (this._core.settings.autoHeight && e.property.name == ‘position’) <
this.update();
>
>, this),
‘loaded.owl.lazy’: $.proxy(function(e) <
if (this._core.settings.autoHeight && e.element.closest(‘.’ + this._core.settings.itemClass)
=== this._core.$stage.children().eq(this._core.current())) <
this.update();
>
>, this)
>;

Which really only added the resized function, but it fixed the issue for me for AutoHeight on a single slide on mobile.

Источник

Самый известный из всех jQuery плагинов для созданием «карусели». Идеальный вариант компактного слайдера для любого контента.

Update: Статья обновлена, актуальная версия плагина — 2+. Первая версия не поддерживается автором плагина.

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

На момент написание данной статьи, демо-страница плагина недоступны, и посмотреть OWL Carousel настройки затруднительно. Возможно, в дальнейшем отображение сайта разработчика будет восстановлена. Ну а мы пока предоставим мануал по использованию плагина со средним содержанием.

Установка плагина

Все исходники плагина находятся в официальном архиве из репозитория на Github (ссылка «Скачать» вверху страницы). В нем располагается папка owl-carousel , которая и содержит все необходимые файлы. Рекомендуем извлечь к себе на сервер все файлы из этой папки (кроме, разве что, не компрессированной версии).

Подключаем обязательные файлы стилей и скриптов:

Для версий 1+

Для версий 2+

Разметка HTML (актуальна для обоих версий)

Настройки OWL Carousel не подразумевают под собой какую-то конкретную разметку по коду. Вы можете применять плагин к любым тегам, главное, чтобы сохранялась следующая структура:

Класс owl-carousel в данном фрагменте служит идентификатором для того, чтобы плагин начал обрабатывать блок, как слайдер. Теоретически, все прямые дочерние элементы будут отдельным слайдами.

Начало работы плагина (актуальна для обоих версий)

Для запуска скрипта достаточно просто объявить его:

Все. После этого Вы уже можете увидеть работу слайдера.

OWL Carousel настройки

Чаще всего требуется кастомизировать работу «карусели» и обозначить параметры под себя. Для этого создано большое количество опций, callback`ов, событий и методов. Мы перечислим лишь самые популярные и необходимые. Вот, что использует плагин OWL Carousel по умолчанию:

Для версий плагина 1+

Для версий плагина 2+

В список включены также опции от встроенных плагинов.

Опция Тип данных По умолчанию Описание
items Number 3 Количество элементов, которые вы хотите увидеть на экране.
margin Number 0 Отступ в пикселях справа от слайда.
loop Boolean false Бесконечная прокрутка элементов.
center Boolean false Отцентровать элемент. Хорошо работает даже с нечетным количеством элементов.
mouseDrag Boolean true Включение перетягивания слайдов мышью.
touchDrag Boolean true Включение перетягивания слайдов на тач-скрине.
pullDrag Boolean true Возможность тянуть слайды за границы.
freeDrag Boolean false Тоже, только к отдельному слайду.
stagePadding Number 0 Отступы слева и справа (чтобы видеть соседние слайды).
merge Boolean false Слияние элементов. Ищет data-merge=’’ внутрли элемента…
mergeFit Boolean true Выбираются объединенные элементы, если экран меньше, чем значение элемента.
autoWidth Boolean false Автоматический подбор ширины. Попробуйте использовать свойства ширины в атрибуте style.
startPosition Number/String 0 Стартовая позиция или URL хэш-строка ‘#id’.
URLhashListener Boolean false Реагировать на изменение хэша URL.
nav Boolean false Выводит кнопки вперед\назад.
rewind Boolean true Вернуться назад, когда граница карусели достигнута.
navText Array [‘next’,’prev’] Текст для кнопок. Поддерживает HTML.
navElement String div Тип элемента DOM для одной направленной навигационной ссылки.
slideBy Number/String 1 Навигация по слайдам x.’страница’.
dots Boolean true Показывать точки навигации.
dotsEach Number/Boolean false Показывать точки каждого элемента X.
dotData Boolean false Использование data-dot содержимого.
lazyLoad Boolean false «Ленивая» загрузка изображений.
autoplay Boolean false Автовоспроизведение.
autoplayTimeout Number 5000 Задержка для автовоспроизведения.
autoplayHoverPause Boolean false Пауза при наведении.
smartSpeed Number 250 Рассчет скорости. Бета.
fluidSpeed Boolean Number Рассчет скорости. Бета.
autoplaySpeed Number/Boolean false Скорость автовоспроизведения.
navSpeed Number/Boolean false Скорость навигации.
dotsSpeed Boolean Number/Boolean Скорость пагинации.
dragEndSpeed Number/Boolean false Скорость при «отпускании» слайда.
callbacks Boolean true Включение событий коллбеков.
responsive Object empty object Объект для опций адаптивности.
responsiveRefreshRate Number 200 Адаптивная частота обновления.
responsiveBaseElement DOM element window Указывает на любой DOM элемент.
video Boolean false Включение выборки с видео-сервисов.
videoHeight Number/Boolean false Установка высоты для видео.
videoWidth Number/Boolean false Установка ширины для видео.
animateOut String/Boolean false Класс для CSS3 анимации исчезновения.
animateIn String/Boolean false Класс для CSS3 анимации появления.
info Function false Обратный вызов для получения базовой информации (текущий элемент/страница/ширина).
nestedItemSelector String/Class false Используйте его, если элементы карусели глубоко вложены в какой-то сгенерированный контент. Не используйте точку перед именем класса.
itemElement String div Тип DOM-элемента для слайда.
stageElement String div Тип DOM-элемента для шага прокрутки.
navContainer String/Class/ID/Boolean false Устанавливает ваш собственный контейнер для навигации.
dotsContainer String/Class/ID/Boolean false Устанавливает ваш собственный контейнер для пагинации.

Скачать плагин версии 2+ можно по ссылке выше.

В случае, если вам нужно посмотреть демо страницу версии 1+, то ее сохранённую копию можно посмотреть из интернет-архива — http://web.archive.org/web/20161022044941/http://owlgraphic.com/owlcarousel/

Там Вы найдете подробные OWL Carousel настройки, а также все возможные примеры использования плагина.

Источник

Читайте также:  Как настроить 4g модем через usb порт роутера netis
Оцените статью