Slick slider arrows не работает

Содержание
  1. Настройки стрелок у Slick слайдера (часть 3)
  2. 1) HTML разметка
  3. 2) Инициализация Slick слайдера
  4. 3) Стилизация Slick слайдера
  5. 4) Настройка стрелок
  6. 5) Делаем слайдер адаптивным
  7. Arrow key navigation not working #901
  8. Comments
  9. lcavezza commented Jan 3, 2015
  10. kenwheeler commented Jan 3, 2015
  11. kenwheeler commented Jan 3, 2015
  12. lcavezza commented Jan 3, 2015
  13. kenwheeler commented Jan 3, 2015
  14. lcavezza commented Jan 4, 2015
  15. ImBobby commented Jan 5, 2015
  16. jmelvnsn commented Jan 8, 2015
  17. ImBobby commented Jan 8, 2015
  18. kenwheeler commented Jan 13, 2015
  19. lcavezza commented Jan 13, 2015
  20. v3nt commented Mar 9, 2016
  21. leggomuhgreggo commented Mar 9, 2016
  22. gitsaagar commented Oct 12, 2016 •
  23. Tantacula commented Oct 17, 2016
  24. gitsaagar commented Oct 17, 2016
  25. davedoesthings commented Feb 6, 2017
  26. davedoesthings commented Feb 7, 2017
  27. simaks commented Mar 15, 2017 •
  28. FoulFoot commented Jul 23, 2017 •
  29. Change the Arrow buttons in Slick slider
  30. 17 Answers 17
  31. .slick-disabled class is not added to arrows when there’s nothing to slide #1244
  32. Comments
  33. herrschuessler commented Apr 17, 2015
  34. simeydotme commented May 11, 2015
  35. herrschuessler commented May 11, 2015
  36. simeydotme commented May 11, 2015
  37. herrschuessler commented May 11, 2015
  38. Slick — лучший адаптивный слайдер для сайта
  39. Примеры использования
  40. Вызов без параметров
  41. Несколько слайдов
  42. Режим центрирования
  43. Адаптивность
  44. Настройки
  45. Методы
  46. События

Настройки стрелок у Slick слайдера (часть 3)

Как показывает практика, для начинающих фронтендеров, самой большой проблемой при кастомизации Slick слайдера, остается настройка стрелок и точек. И если со стилизацией индикаторных точек, мы разобрались на прошлом уроке, то сегодня мы научимся заменять дефолтные стрелки на свои (по макету).

1) HTML разметка

У вас уже должна быть подключена библиотека jQuery и файл самого слайдера slick.min.js. Создадим контейнер для слайдера, внутри которого 6 слайдов с картинками.

2) Инициализация Slick слайдера

Создаем файл script.js и подключаем ранее созданный контейнер для слайдов с классом slider к Slick слайдеру.

$(document).ready(function() <
$(‘.slider’).slick( <
arrows:true, // показать стрелки
dots:false, // не показывать точки
slidesToShow:3, // показывать по 3 слайда
autoplay:true, // автоматическое проигрывание слайдов
>);
>);

После инициализации слайдера, автоматически создались новые теги, а к элементам добавились новые классы (смотрите инструменты разработчика). Через эти классы мы будем управлять внешним видом слайдера в CSS файле (style.css).

3) Стилизация Slick слайдера

Все слайды выстроим в ряд и прибьем их к верхнему краю.

.slick-track <
display: flex;
align-items: flex-start;
>

Спрячем в ограничивающей оболочке слайдера, контент (картинки), выходящий за её пределы.

.slick-list <
overflow: hidden;
>

Зададим промежутки между слайдами и сделаем картинки адаптивными.

.slider__item <
padding: 0px 15px;
>

.slider__item img <
max-width: 100%;
>

4) Настройка стрелок

Данная настройка заключается в замене дефолтных стрелок, на свои. Зададим абсолютное позиционирование для своих стрелок относительно слайдера.

.slider <
position: relative;
padding: 0px 60px; // поля между стрелкой и краем слайдера
>

.slider .slick-arrow <
position: absolute;
top: 50%; // выравнивание по вертикали
margin: -15px 0 0 0; // корректировка вертикального выравнивания
z-index: 2; // стрелки сверху картинок
font-size: 0; // убираем надпись на дефолтной стрелке
width: 30px; // ширина стрелки
height: 30px; // высота стрелки
>

Вставляем фоном заранее заготовленные свои стрелки (вырезаем из макета)

.slider .slick-arrow.slick-prev <
left: 0; // левая стрелка остается с левой стороны слайдера
background: url(‘../img/left-arrow.png’) 0 0 / 100% no-repeat;
>

.slider .slick-arrow.slick-next <
right: 0; // правая стрелка переместилась справа от слайдера
background: url(‘../img/right-arrow.png’) 0 0 / 100% no-repeat;
>

5) Делаем слайдер адаптивным

Добавим в JS файл свойство responsive со следующими настройками: При максимальной ширине окна 768 пикселей, показывать 2 слайда, а при максимальной ширине окна 550 пикселей — 1 слайд.

responsive:[
<
breakpoint: 768,
settings: <
slidesToShow:2
>
>,
<
breakpoint: 550,
settings: <
slidesToShow:1
>
>
]

Источник

Arrow key navigation not working #901

Comments

lcavezza commented Jan 3, 2015

Autoplay working well, but draggable and accessibility aren’t working. The slides can’t be dragged or moved with the right/left arrow keys.

Читайте также:  Приложение не работает с новой версией ios

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

kenwheeler commented Jan 3, 2015

Have you tabbed to slick?

kenwheeler commented Jan 3, 2015

Also, what browser

lcavezza commented Jan 3, 2015

Not working in both Chrome and Safari —

Sorry, unsure what you mean by tabbed to slick?

kenwheeler commented Jan 3, 2015

I would need to see a JSFiddle to diagnose what’s going on there

lcavezza commented Jan 4, 2015

It isn’t swiping on mobile, and also the right and left arrow keys don’t work to move through the slides on desktop.

ImBobby commented Jan 5, 2015

The slides can’t be dragged or moved with the right/left arrow keys

just visited the fiddle, and it is draggable and left/array keys are working as expected. Tried in both Chrome and Safari.

jmelvnsn commented Jan 8, 2015

I am experiencing a similar issue. Arrow nav is not activated on initial page load. Only when I drag the slide once do the arrow keys work. Seeing the same behavior in the above jsfiddle in Chrome and Firefox.

ImBobby commented Jan 8, 2015

Ah, I get the picture now. The arrow keys are working only if the slider is focused. I revisited the fiddle above, and yes during initial load the arrow keys are not working. That’s because the focused element is not the slider.

If you interact with the slider, either you click or drag it, then the arrow keys work.

kenwheeler commented Jan 13, 2015

Yeah the reason is because if you have more than one, which one does it work for? You can manually rig this up using the slickNext/Prev methods and a key listener if you want.

lcavezza commented Jan 13, 2015

Thanks, @kenwheeler. I figured out the problem I was having, it was because I was using SVGs, and they were wrapped in «object» tags. This caused the jquery events to not fire.

Appreciate the help!

v3nt commented Mar 9, 2016

is there a way we can set the slider as focused when the page loads? ie so the keypresses work straight away?

leggomuhgreggo commented Mar 9, 2016

gitsaagar commented Oct 12, 2016 •

@leggomuhgreggo : I don’t think that helps.
Can you please check this link and suggest where am I going wrong?
I added onload event as you suggested but the keyboard arrows doesn’t seem to work on slider directly without clicking on slider, after a page load or reload.
http://www.umbrella-technologies.com/dev/swipe/

Tantacula commented Oct 17, 2016

@gitsaagar Yes, .focus() will not work on divs and lists. Looks like the only solution is use key events

gitsaagar commented Oct 17, 2016

@Tantacula : Thankyou . Appreciate the Help!

davedoesthings commented Feb 6, 2017

Has anyone mastered getting the carousel to take keyboard focus programmatically? Really keen to be able to automatically give the carousel focus on a particular screen, but seem to be banging my head against a wall.

I’ve tried targeting the .slick-list element, adding tabindex=0 and then calling focus() but no joy.

davedoesthings commented Feb 7, 2017

This got it to work in the end $(document).find(‘.slick-list’).attr(‘tabindex’, 0).focus();

simaks commented Mar 15, 2017 •

also you can try adding atribute [tabindex=»-1″] to the .slider element, and then $(‘.slider’).focus() trick should start working. Tested on bootstraps carousel https://v4-alpha.getbootstrap.com/components/carousel/
Thats because element must be focusable before you try to focus it

FoulFoot commented Jul 23, 2017 •

This took me a couple of hours; I couldn’t get any of the above suggestions to work:

— $(‘.slider’).focus() doesn’t work; it correctly focuses on the slider, but it needs to focus on the first image in the slider.
— I couldn’t get $(document).find(‘.slick-list’).attr(‘tabindex’, 0).focus(); to work. Probably because there’s other elements on my page that have a tabindex of zero. Trying to set the tabindex manually to something like 25 doesn’t work; Slick overwrites it with its own tabindex values.

Читайте также:  У меня не работает speedtest

My solution was to give the «a» tag around the first image an id of «slicker». Then on pageload, grab the element (the «a» tag) with that id and focus on it.

Hope this helps someone.

( and to get rid of the blue focus border, add a «style=»outline:none;»» attribute to the «a» tag).

Источник

Change the Arrow buttons in Slick slider

I want to change the arrows in my slick slider but it does not change. I want the next and previous button as an image. I have tried putting it in a but it still not working. Where can I change the arrows setting?

slick theme css @charset «UTF-8»;

slick css

17 Answers 17

Slick has a very easy way to customize its buttons through two variables in its own configuration: prevArrow and nextArrow .

Both types are: string (html | jQuery selector) | object (DOM node | jQuery object), so in your settings slick slider you can set the classes:

and add to these elements the styles you want.

You can easily create your own style of arrow with the .slick-next:before and the .slick-prev:after pseudo-classes.

Here’s an example:

its very easy. Use the bellow code, Its works for me. Here I have used fontawesome icon but you can use anything as image or any other Icon’s code.

This worked for me:

Hide the default buttons in CSS and use:

Image URLs can be local or cdn-type stuff (web icons, etc.).

Example CSS (adjust as needed here, this is just an example of what’s possible):

This worked well for me!

If you are using sass you can simply set below mentioned variables,

These will change the font family used by slick’s theme css and also the unicode for prev and next button.

Other sass variables which can be configured are given in Slick Github page

You can use FontAwesome «content» values and apply as follow by css. These apply «chevron right/left» icons.

The Best way i Found to do that is this. You can remove my HTML and place yours there.

Content property of pseudo element :before accepts images too. In slick-theme.css change:

or directly change the content property on slick-prev:before and slick-next:before

here is another example for changing the arrows and using your own arrow-images.

Here’s an alternative solution using javascipt:

Change the img to text or what ever you require.

Here is my example of how to change the arrows for Slick Carousel in React to anything you would like. First you need to set the nextArrow and prevArrow in settings to a function then return a div in that function with whatever icon you would like to use. For mine I used Font Awesome. Then you will need to add a className in your icon, you will see that in the NextArrow and PrevArrow functions. Then add the scss code to customize whatever you would like.

For changing the color

if your using react-slick you can try this on custom next and prev divs

If we want to use font awesome library using the css then we can use the below css

Font awesome library css must be added in the page.

Источник

.slick-disabled class is not added to arrows when there’s nothing to slide #1244

Comments

herrschuessler commented Apr 17, 2015

When the total number of slides matches the number of slides to display at the same time, and looping is disabled, the arrows should receive the CSS class .slick-disabled, but that class is not applied.

Example: The slider is showing 3 slides simultaneously. There are only 3 slides in the slider. Arrows should be disabled, because scrolling is impossible.

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

Читайте также:  Почему не работает шуруповерт макита

simeydotme commented May 11, 2015

Arrows are not rendered, so no class can be applied.
http://jsfiddle.net/simeydotme/aj7ftgmt/

herrschuessler commented May 11, 2015

You are right — when using the generated arrows, no class can be applied.

When using custom arrows (via the prevArrow / nextArrow setting), the issue still exists.
https://jsfiddle.net/twpyfyoy/7/

simeydotme commented May 11, 2015

Aha. Touché!
Well, I will investigate if this is simple or not, in the mean-time you could always use the breakpoint event to detect if slidesToShow === $slides.length 🙂

herrschuessler commented May 11, 2015

Thanks! For now I’ll just take advantage of the fact that slick adds an inline declaration of display:block to the arrows and hide them by default, so that no arrows are shown when there’s nothing to slide.

Источник

Slick — лучший адаптивный слайдер для сайта

Slick slider — это jQuery плагин для быстрого создания на сайте адаптивного слайдера любой сложности. Его функционал позволяет реализовать зацикливание, автопроигрывание, эффекты перехода и многое другое. Отдельно выделю возможность пролистывания слайдера пальцем на устройствах с сенсорным экраном.

Подключение осуществляется следующим образом.

Подготавливаем разметку. Для этого каждый слайд оборачиваем в «div», внутри которого будет какое-то содержимое:

Примеры использования

Рассмотрим примеры вызова «Slick slider» с разными настройками.

Вызов без параметров

При вызвове без параметров получим один активный слайд с навигационными стрелками.

Несколько слайдов

Отобразим 3 слайда с параметрами зацикленной прокрутки (infinite), отображением навигационных точек (dots) и количеством прокручиваемых за раз слайдов (slidesToScroll).

Режим центрирования

В режиме центрирования активный слайд устанавливается по центру с классом «slick-center».

Адаптивность

Если на сайте адаптивная верстка, то слайдер можно подстроить под ширину экрана. Для этого используйте свойство «responsive». Оно позволяет установить для разных разрешений индивидуальные настройки. Рассмотрим пример.

Здесь по умолчанию устанавливается отображение в ряд 3 слайда. Если ширина видимой области браузера от 768 до 481 пикселя — 2. И один, если ширина менее 480 пикселей.

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

Настройки

В таблице приведены основные настройки. Полный перечень на сайте разработчика.

Параметр Тип Default Описание
adaptiveHeight boolean false Включает адаптирование высоты для одиночкного слайда горизонтальной карусели
autoplay boolean false Автоматическая прокрутка
autoplaySpeed int(ms) 3000 Скорость автопрокрутки в милисекундах
arrows boolean true Показ/скрытие навигационных кнопок
prevArrow html button Замена стандартной кнопки Preview
nextArrow html button Замена стандартной кнопки Next
dots boolean false Показ/скрытие навигационных точек под слайдером
draggable boolean true Включает/выключает способность перелистывания слайдера перетаскиванием мышью
fade boolean false Эффект затухания при перелистывании слайдов
focusOnSelect boolean false Устанавливает фокус на выбранный элемент карусели при клике
easing string ‘linear’ Анимационные эффекты перехода, их набор зависит от подключенных jQuery Easing плагинов
edgeFriction integer 0.15 Сопротивление при попытки прокрутить карусель, когда дальше нет слайдов и она не зацилена
infinite boolean true Бесконечное прокручивание (зацикливание)
initialSlide integer 0 Номер слайда, с которого начинать показ
lazyLoad string ‘ondemand’ Тип подгрузки слайдов. Принимает ‘ondemand’ или ‘progressive’
pauseOnHover boolean true Пауза автопроигрывания при наведении мыши
pauseOnDotsHover boolean false Пауза автопроигрывания при наведении мыши на навигационные точки
pauseOnHover boolean true Пауза автопроигрывания при наведении мыши
rows int 1 Может быть ‘window’, ‘slider’ или ‘min’

Методы

Методы — это функции, которые могут совершить со слайдером какие-то действия или сообщать о его текущем состоянии. Метод можно вызывать в любом JS обработчике, например, при нажатии на кнопку.

slickCurrentSlide — возвращает номер текущего слайда. Отсчёт ведётся с нуля.

slickGoTo — переходит к слайду с указанным номером.

slickNext — прокручивает на один слайд вперёд.

slickPrev — прокручивает на один слайд назад.

slickPause — останавливает автоматическую прокрутку.

slickPlay — запускает автоматическую прокрутку.

События

События позволяют реагировать на определенные действия. Например, после прокрутки к 5 слайду выведем сообщение. Для этого включаем обработчик события « afterChange ».

« beforeChange » срабатывает перед переходом к другому слайду:

Источник

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