- Не работает slick слайдер, почему?
- Responsive breakpoints not working for slick slider
- 6 Answers 6
- Reinit slider when leaving a breakpoint with settings: ‘unslick’ #1190
- Comments
- alexej-d commented Mar 29, 2015
- aldidas commented Apr 29, 2015
- simeydotme commented Apr 29, 2015
- stevegrunwell commented Mar 7, 2017
- Grawl commented Jul 20, 2017
- romannikiforov commented Dec 7, 2018
- CornerstoneII commented Sep 24, 2020
- stevegrunwell commented Sep 25, 2020
- dalaranunion commented Jun 8, 2021 •
- Как решить проблему с двумя slick-слайдерами на странице?
- slick
- slick
- Features
- Single Item
- Multiple Items
- Responsive Display
- Variable Width
- Adaptive Height
- Data Attribute Settings
- Center Mode
- Lazy Loading
- Autoplay
- Add & Remove
- Filtering
- Destroy
- Slider Syncing
- Right to Left
- and a whole lot more.
- Getting Started
- Settings
- Events
- Methods
- WordPress
- Go Get It
Не работает slick слайдер, почему?
Всем привет. Все сделал как в документации, но он почему то не работает.. Причем вроде как подключился, но криво. Один из элементов вылазит слева страницы, причем его можно листать, но он не листается, от начала до конца страницы только двигается.. Потом вообще исчезает.. Что не так с этим слайдером?
- Вопрос задан более трёх лет назад
- 4698 просмотров
1 что надо всегда делать, это смотреть на ошибки в консоле, но допустим их там нет, тогда:
Почему тема перед основными стилями?
Убедитесь что $(‘.single-item’) находит, например так:
console.log($(‘.single-item’).length);
выведет в консоль 1 если все ок.
тут явно одна строка лишняя
ну и да, вызывать слик после модалки, причем не просто после модалки, а по событию окно построено. погуглите немножко, все есть там.
для скрытых блоков слик не пашет, это так со всеми слайдерами будет, увы и ах))) или пишите свой слайдер, теоретически можно и на скрытых делать, но будет топорно выглядеть.
Источник
Responsive breakpoints not working for slick slider
I have implemented slick slider which works fine without resizing the browser. But when I resize the browser to 1024 then the responsive breakpoint settings doesn’t work.
Any help is highly appreciated.
6 Answers 6
Add this settings to your code;
Add slidesToShow and slidesToScroll option in each breakpoint.
First of all, «variableHeight» option does not exist in Slick Carousel.
To solve your issue, remove variableWidth: true , because this will make your slides take full with of the carousel. And you can also not use «mobileFirst» option if your page is not using this methodology.
So finally your config should be like this, below
This did the trick for me.
Add this to your js and call the slider as shown.
and in your css make the slide display: inline-block; that’s it. will work on all responsive screens.
I am not sure why your js template is failing with below:
I would follow up with their documentation, community, or file a bug.
In any case it is better practice to use CSS3 media queries for this. One approach; nest a div around the slider and position it relative , scale it and it’s child elements with width: 100%; and declaring max and min width ‘s within defined resolutions. This should start you in the right direction. Make sure to also make proper use of meta viewport.
Источник
Reinit slider when leaving a breakpoint with settings: ‘unslick’ #1190
Comments
alexej-d commented Mar 29, 2015
Hey there,
really love your plugin, I use it in nearly every project – thanks for the great work.
I observed a counter-intuitive behaviour with the following init code:
One would expect that once leaving the breakpoint the slider reinitializes but it is not the case. Am I missing something?
The text was updated successfully, but these errors were encountered:
aldidas commented Apr 29, 2015
In my recent project, I was facing this issue and ended up to assign the slick() initialization inside another function. So we can listen to jQuery’s $(window).resize(), and re-init the slick when the window’s width reach the breakpoint. Here is my code :
Suggestions open for any better solution 🙂
simeydotme commented Apr 29, 2015
It’s dubiously documented here: https://github.com/kenwheeler/slick/releases/tag/1.4.0 — No current plans to change this. Better to use the window.resize event if you plan on removing carousels 🙂
stevegrunwell commented Mar 7, 2017
Hopefully this helps someone else 🙂
Grawl commented Jul 20, 2017
my dirty try on this:
romannikiforov commented Dec 7, 2018
CornerstoneII commented Sep 24, 2020
Hopefully this helps someone else 🙂
Error on this page
stevegrunwell commented Sep 25, 2020
Oh no! I left the company several years ago, they must have taken down the engineering blog 😢 . I’ll reach out to the CEO and see if it can get reinstated (or if I can get copies of the posts to put elsewhere).
Thanks for the heads up!
dalaranunion commented Jun 8, 2021 •
Heya I was looking for a solution to this and I thought I should paste one here.
Assuming you ‘unslick’ slideshow(s) because you would like to save browser resources and then «slick» them once the size of the window increases, I think ‘resize’ events should be throttled. But anyway here is a nasty implementation.
Источник
Как решить проблему с двумя slick-слайдерами на странице?
Друзья, поставил на свой лендинг два разных slick-слайдера. Для каждого из них прописал отдельные свойства и путь к файлам JS и CSS в файле index:
Файлы style.css и common.js общие.
При загрузке страницы ОБА слайдера почему-то используют те данные, которые записаны в slick1. Как я ни пытался добиться того, чтобы они использовали разные свойства, у меня ничего не получается. В чём может быть проблема?
Я новичок в html/css/js, поэтому буду рад любой помощи. Спасибо!
- Вопрос задан более года назад
- 1404 просмотра
Простой 1 комментарий
Вам следует использовать по одному css и js файлу для любого количестве slick-слайдеров на странице.
Если оба слайдера используют одни и те же данные, то тут всего 2 варианта:
1) Вы по ошибке указали один и тот же объект в качестве настроек для обоих слайдеров,
2) Вы инициализировали действительно слайдеры с разными настройками, на одном и том же селекторе.
P.s.Если оба варианта Вам не подходят — приложите js код (можно вместе с html), а то кроме как догадок\предположений ничего не получите.
Вы можете подключить 1 CSS и 1 JS файл к вашему html.
Просто при инициализации используйте разные названия каруселей.
И свойства кидайте на вот эти классы slick1, slick2
Источник
slick
the last carousel you’ll ever need
slick
the last carousel you’ll ever need
Features
- Fully responsive. Scales with its container.
- Separate settings per breakpoint
- Uses CSS3 when available. Fully functional when not.
- Swipe enabled. Or disabled, if you prefer.
- Desktop mouse dragging
- Infinite looping.
- Fully accessible with arrow key navigation
- Add, remove, filter & unfilter slides
- Autoplay, dots, arrows, callbacks, etc.
Single Item
Multiple Items
Responsive Display
Variable Width
Adaptive Height
Data Attribute Settings
In slick 1.5 you can now add settings using the data-slick attribute. You still need to call $(element).slick() to initialize slick on the element.
Center Mode
Lazy Loading
Autoplay
Add & Remove
Filtering
Destroy
If you really want to be that guy.
Slider Syncing
Right to Left
Note: the HTML tag or the parent of the slider must have the attribute «dir» set to «rtl».
and a whole lot more.
Getting Started
Set up your HTML markup.
Move the /slick folder into your project
Add slick.css in your
Add slick.js before your closing tag, after jQuery (requires jQuery 1.7 +)
Initialize your slider in your script file or an inline script tag
When complete, your HTML should look something like:
NOTE: I highly recommend putting your initialization script in an external JS file.
Settings
| Setting | Type | Default | Description |
|---|---|---|---|
| accessibility | boolean | true | Enables tabbing and arrow key navigation |
| adaptiveHeight | boolean | false | Enables adaptive height for single slide horizontal carousels. |
| autoplay | boolean | false | Enables Autoplay |
| autoplaySpeed | int(ms) | 3000 | Autoplay Speed in milliseconds |
| arrows | boolean | true | Prev/Next Arrows |
| asNavFor | string | null | Set the slider to be the navigation of other slider (Class or ID Name) |
| appendArrows | string | $(element) | Change where the navigation arrows are attached (Selector, htmlString, Array, Element, jQuery object) |
| appendDots | string | $(element) | Change where the navigation dots are attached (Selector, htmlString, Array, Element, jQuery object) |
| prevArrow | string (html|jQuery selector) | object (DOM node|jQuery object) | Previous | Allows you to select a node or customize the HTML for the «Previous» arrow. |
| nextArrow | string (html|jQuery selector) | object (DOM node|jQuery object) | Next | Allows you to select a node or customize the HTML for the «Next» arrow. |
| centerMode | boolean | false | Enables centered view with partial prev/next slides. Use with odd numbered slidesToShow counts. |
| centerPadding | string | ’50px’ | Side padding when in center mode (px or %) |
| cssEase | string | ‘ease’ | CSS3 Animation Easing |
| customPaging | function | n/a | Custom paging templates. See source for use example. |
| dots | boolean | false | Show dot indicators |
| dotsClass | string | ‘slick-dots’ | Class for slide indicator dots container |
| draggable | boolean | true | Enable mouse dragging |
| fade | boolean | false | Enable fade |
| focusOnSelect | boolean | false | Enable focus on selected element (click) |
| easing | string | ‘linear’ | Add easing for jQuery animate. Use with easing libraries or default easing methods |
| edgeFriction | integer | 0.15 | Resistance when swiping edges of non-infinite carousels |
| infinite | boolean | true | Infinite loop sliding |
| initialSlide | integer | 0 | Slide to start on |
| lazyLoad | string | ‘ondemand’ | Set lazy loading technique. Accepts ‘ondemand’ or ‘progressive’ |
| mobileFirst | boolean | false | Responsive settings use mobile first calculation |
| pauseOnFocus | boolean | true | Pause Autoplay On Focus |
| pauseOnHover | boolean | true | Pause Autoplay On Hover |
| pauseOnDotsHover | boolean | false | Pause Autoplay when a dot is hovered |
| respondTo | string | ‘window’ | Width that responsive object responds to. Can be ‘window’, ‘slider’ or ‘min’ (the smaller of the two) |
| responsive | object | none | Object containing breakpoints and settings objects (see demo). Enables settings sets at given screen width. Set settings to «unslick» instead of an object to disable slick at a given breakpoint. |
| rows | int | 1 | Setting this to more than 1 initializes grid mode. Use slidesPerRow to set how many slides should be in each row. |
| slide | element | » | Element query to use as slide |
| slidesPerRow | int | 1 | With grid mode intialized via the rows option, this sets how many slides are in each grid row. dver |
| slidesToShow | int | 1 | # of slides to show |
| slidesToScroll | int | 1 | # of slides to scroll |
| speed | int(ms) | 300 | Slide/Fade animation speed |
| swipe | boolean | true | Enable swiping |
| swipeToSlide | boolean | false | Allow users to drag or swipe directly to a slide irrespective of slidesToScroll |
| touchMove | boolean | true | Enable slide motion with touch |
| touchThreshold | int | 5 | To advance slides, the user must swipe a length of (1/touchThreshold) * the width of the slider |
| useCSS | boolean | true | Enable/Disable CSS Transitions |
| useTransform | boolean | true | Enable/Disable CSS Transforms |
| variableWidth | boolean | false | Variable width slides |
| vertical | boolean | false | Vertical slide mode |
| verticalSwiping | boolean | false | Vertical swipe mode |
| rtl | boolean | false | Change the slider’s direction to become right-to-left |
| waitForAnimate | boolean | true | Ignores requests to advance the slide while animating |
| zIndex | number | 1000 | Set the zIndex values for slides, useful for IE9 and lower |
Events
In slick 1.4, callback methods have been deprecated and replaced with events. Use them as shown below:
| Event | Arguments | Description |
|---|---|---|
| afterChange | slick, currentSlide | Fires after slide change |
| beforeChange | slick, currentSlide, nextSlide | Fires before slide change |
| breakpoint | event, slick, breakpoint | Fires after a breakpoint is hit. |
| destroy | event, slick | When slider is destroyed, or unslicked. |
| edge | slick, direction | Fires when an edge is overscrolled in non-infinite mode. |
| init | slick | Fires after first initialization. |
| reInit | slick | Fires after every re-initialization |
| setPosition | slick | Fires after position/size changes |
| swipe | slick, direction | Fires after swipe/drag |
| lazyLoaded | event, slick, image, imageSource | Fires after image loads lazily |
| lazyLoadError | event, slick, image, imageSource | Fires after image fails to load |
Methods
Methods are called on slick instances through the slick method itself in version 1.4, see below:
This new syntax allows you to call any internal slick method as well:
| Method | Arguments | Description |
|---|---|---|
| slickCurrentSlide | none | Returns the current slide index |
| slickGoTo | int : slide number, boolean: dont animate | Navigates to a slide by index |
| slickNext | none | Navigates to the next slide |
| slickPrev | none | Navigates to the previous slide |
| slickPause | none | Pauses autoplay |
| slickPlay | none | Starts autoplay |
| slickAdd | html or DOM object, index, addBefore | Add a slide. If an index is provided, will add at that index, or before if addBefore is set. If no index is provided, add to the end or to the beginning if addBefore is set. Accepts HTML String || Object |
| slickRemove | index, removeBefore | Remove slide by index. If removeBefore is set true, remove slide preceding index, or the first slide if no index is specified. If removeBefore is set to false, remove the slide following index, or the last slide if no index is set. |
| slickFilter | Selector or Function | Filters slides using jQuery .filter() |
| slickUnfilter | index | Removes applied filtering |
| slickGetOption | option : string | Gets an individual option value. |
| slickSetOption | option : string, value : depends on option, refresh : boolean | Sets an individual value live. Set refresh to true if it’s a UI update. |
| unslick | none | Deconstructs slick |
| getSlick | none | Get Slick Object |
WordPress
Go Get It
You can also use slick with the jsDelivr CDN!
If you like slick, and also like Sass, try my Guff mixin library!
Источник