background

Among the many needs of marketing, there are many needs for card slides. Such as: pop-up advertising space, share pop-up, card animation and so on.

I’ve tried Swiper before, but it feels a bit big…

Keen-slider was chosen

1. Small size

  • Keen-slider is packed and compressed to a size of 28kb.
  • Swiper packs 364KB.

2. The document is easy to read

keen-slider.io/examples

Swiperjs.com/react#usage…

3. Dependent third-party libraries

  • Keen-slider only relies on React, which is compatible with upgrades

Keen – the use of the slider

Keen-slider provides a hook for react. Like all React hooks, useKeenSlider can only be called from the top layer of the component (not in if else). It accepts two parameters, Options (the first parameter) and Plugins (the second parameter). UseKeenSlider returns an array. The first element of the array is a callback function bound to the slider, and the second element is an instance of the slide, or a variable that contains the specific properties of the slide.

import React from 'react'
import 'keen-slider/keen-slider.min.css'
import { useKeenSlider } from 'keen-slider/react' // import from 'keen-slider/react.es' for to get an ES module

export default() = > {// 1. The first parameter is finally bound to the outermost layer of keen-slider
  // 2. Slider can access the slider instance with the second argument
  const [refCallback, slider] = useKeenSlider(
	// Options
    {
      rtl: true.slideChanged() {
        console.log('slide changed')}},// Plugins
    [
      // add plugins here])return (
    <div ref={refCallback} className="keen-slider">
      <div class="keen-slider__slide">1</div>
      <div class="keen-slider__slide">2</div>
      <div class="keen-slider__slide">3</div>
    </div>)}Copy the code

Keen-slider Options property

You can customize slides with different effects by passing in Options (including event hooks). If you want to change the configuration after initialization, you can call the Update method to do so.

1. breakpoints:object

Override the options and Event hooks property values under certain conditions. Each specific condition must be a string of media queries. Orientation: portrait and (min-width: 500px) Note: If multiple media queries are valid at the same time, the last one prevails.

new KeenSlider('#my-slider', {
  loop: true.breakpoints: {
    // The loop property changes to false when the width is less than 500px.
    '(min-width: 500px)': {
      loop: false,}}})Copy the code

Official Breakpoint example

2. defaultAnimation:object

Set up animation functions for next, Prev, moveToIdx actions.

  • duration: number – Duration of the animation in milliseconds
  • easing: function – change function (time: number) => number

3. disabled: boolean

If this property is true, the slider is disabled. No events or styles are invalidated. The default value is false.

4. drag: boolean

Turn on or off responses to mouse and Touch events. The default is true.

5. dragSpeed: number | function

Set the movement speed when being dragged. It could be a specific number, it could be a function. Negative values will reverse the slide. The default value is 1

6. initial: number

Sets the initial index of the slide. The default value is 1 (subscripts start at 1).

7.loop: boolean | object

Enable/disable loop mode for slides. Of course, you can also pass min, Max specified number of cycles.

8. mode: ‘snap’ | ‘free’ | ‘free-snap’

Set animation mode after drag ends. The default for the snap

9. range: object

Regardless of how many sliders are included in the viewport, you can specify accessible sliders.

  • min: number: Sets the minimum accessible subscript
  • max:number: Sets the maximum accessible subscript
  • align:boolean: Aligns the maximum position to the end of the last slider

10. renderMode: ‘precision’ | ‘preformance’ | ‘custom’

If your slider has complex markup and CSS, rendering performance may be slow. To solve this problem, you can set this option to Performance. If you want to create your own renderer, you can set this option to Custom. The default setting is precision.

11. rtl: boolean

Change the display position of the slider. Change left to right to right to left. The default value is false

12. rubberband: boolean

Enables or disables the slider drag behavior and animation after the drag. The default is true.

13. selector: string | HTMLElement[] | NodeList | function | null

Specifies how to receive a slider from the DOM. This can be a CSS selector, a collection of HTMLElements, a function to get containers, or NULL. Set this property to NULL if you do not want the slider to position or scale the slide.

14. slides: object | number | function | null

Specify the configuration of the slide. The slide configuration is updated every time it is updated, resized, or changed. Therefore, all functions are called again. The default is null.

  • Number – Sets the number of slides to the specified number.

  • Object – This object is used to specify slide configuration.

    • Origin: ‘auto’ | ‘center’ | ‘number’ – the origin of setting the slider.

      Auto: Adjusts the origin of all slides so that the first slide is aligned to the left and the last slide to the right.

      Center: Center all slides.

      Number: relative to viewport??

    • Number: number | function | null – if the value of digital or null, is similar to the slides. It can also be a function that returns a number or null. The default value is null.

    • PerView: number | function | ‘auto’ – determine the slides should be related to the viewport/container size. If set to automatic, the slide size is determined based on the size of the corresponding HTML element. Therefore, the selector option must not be empty. It can also be a function that returns a number or ‘auto’. The default value is 1.

    • Spacing: number | function – the spacing between the pixel defining slide. It could be a function that returns a number. The default value is 0.

  • Function – Specifies a slide configuration using a function that returns an array of slide configurations. Slide configuration has the following optional properties.

    • origin: number– Determine the position of the slide’s origin in the viewport. The default value is0.
    • size: number– Determine the relative size of the slide relative to the viewport. The default value is1.
    • spacing: number– Determine the distance from a slider. The default is0.

The first argument to the function is the size of the container, and the second argument is a slide of the ARRAY of HTML elements.

  • null– The style of the slider will be determined by the selector property.

15. vertical: boolean

Change the orientation of the slider from horizontal to vertical. The default value is false.

Event Hooks

Event hooks are functions that the slider calls during its life cycle. The function takes Properties as its only argument. The event hook is part of the Option argument (the first argument to useKeenSlider). Here are the event functions that fire.

1. animationStarted

The declared periodic function called when the animation begins. The animation occurs after a drag or when moveToIdx() or animator.start() is called.

2. animationStop

Called when the animation stops.

3. animationEnded

Called when the animation ends.

4. created

Called when the slider is created.

5. destroyed

Called when the slider is destroyed

6. detailsChanged

Fired when the Details property changes. Triggered every time the slider moves, or the slide configuration changes, initializes or resizes.

7. dragged

Called when the slider is being dragged.

8. dragStarted

Called when the slider starts dragging.

9. dragChecked

The drag direction is checked and valid.

10. dragEnded

Called when the slider starts dragging and ends.

11. optionsChanged

The configuration of slides changes, for example due to updates, resizing (when the number of slides changes), or breakpoints changes.

12. slideChanged

Triggered when the current slider or most sliders have changed.

13. updated

Called when the update function is triggered due to a size change or other change.

Method && property

Whether the slider is created via React Hook or plain javascript, it returns an instance or a property object for further manipulation. These properties are described below.

Animator:object

Animator is the module responsible for motion animation of tracks. It has the following properties:

  • Active: Boolean – Indicates whether the animation is running.

  • Start: function – Starts a new animation. You need an array of keyframes. Keyframes are processed sequentially.

    slider.animator.start([keyframe1, keyframe2])
    Copy the code

    A keyFrame contains the following properties:

    • distance: number – The distance moved in the animation.
    • duration: number – Duration of the animation in milliseconds.
    • earlyExit: number – Optionally sets an earlier keyframe termination.
    • easing: function – animation function (time: number) => number.
  • Stop: function – Stops the currently active animation (if any).

  • TargetIdx: number | null – at the end of the animation in the active state index.

container: HTMLElement

HTML element, a container for slides.

destroy: function

The destroy function destroys the slider when called, and all events and application styles are removed.

on: function

slider.on(eventName, callback, remove)
Copy the code

Registers an event hook when called.

  • eventName: string – Specifies the event name.
  • callback: function – When this event is raised, this function will be executed.
  • remove: Boolean – Whether the function should be set or deleted. The default isfalse.

emit: function

slider.emit(eventName)
Copy the code

Events are emitted when called. An eventName: String is required as an argument.

moveToIdx: function

slider.moveToIdx(index, absolute, animation)
Copy the code

The active slide is animated when called.

  • index: number – Specifies the active slider subscript
  • absolute: Boolean – Defines whether the index is absolute. The default isfalse.
  • animation: object – Changes the default animation. Objects can have the following properties
    • duration: number – Sets the animation duration to milliseconds. The default is 500.
    • easing: function – Sets the palliative function. The default is t => 1 + — t * t * t * t.

next: function

Changes the current active slide to the previous one (if one exists) when called.

prev: function

Changes the current active slide to the latter one, if one exists, when called.

size: number

Viewport width/height depends on how the slide is arranged horizontally/vertically.

slides: HTMLElement[]

Slides as an array of HTML elements.

track: object

  • AbsToRel: function – Converts absolute indexes to corresponding relative indexes.

  • Add: function – Adds the passed value to the trace position.

  • Details: object | null – the current position of the slider, length, size and distance relative to the container/size of the viewport. Set to NULL if the slider is disabled or not ready.

    • abs: absolute index of the number-active slider.
    • length: number – The relationship between the current slider length and viewport size. .
    • min: number – The smallest position calculated from the range/loop variable.
    • max: number – The maximum position calculated from the range/loop variable.
    • minIdx: number – The minimum subscript calculated from the range/loop variable.
    • maxIdx: number – The maximum index calculated from the range/loop variable.
    • position: number – The current position calculated from the range/loop variables.
    • progress: number – The position of the slider relative to its length.
    • rel: number – The relative index of the current active slider.
    • slides: array – Details for each slider that acts as an array of objects. Each object has the following properties.
      • abs: absolute index of the number-active slider.
      • distance: number – The distance from the slider to the beginning of the viewport.
      • portion: number – Indicates how many slides are visible in the viewport.
      • size: number – Size of the slider relative to the viewport.
    • distToIdx: function – Converts the passed distance to the corresponding index.
    • idxToDist: function – Returns the distance of the passed index. The second argument, optional, is a Boolean value that specifies whether the index passed in is absolute. The third argument is optional and specifies the reference location.
    • init: function – reinitializes the track. You can reset the active slider here.
    • to: function – Sets the value passed to the slider position.
    • velocity: function – Returns the current speed of the slider.

update: function

slider.update(options, idx)
Copy the code

If resizing is triggered or configuration changes need to be made, the update function can be called to forcibly update the slides.

  • options: object – Specifies the new configuration for which the slider should be reinitialized. The default valueundefined.
  • idx: number – Sets the current active slide to the given index. The default isundefined.

Built-in CSS properties

  • data-keen-slider-clickable– Setting this property on each slider organizes touch/click events on the slider.
  • data-keen-slider-scrollable– Sets this property on each slider, allowing the slider to slide horizontally/vertically.overflowYou need to set it toscroll.

Keen-slider plugin

To make integration, structure, and versioning of custom slider functions easier, you can create plug-ins. Keen-slider itself is also partly plug-in based.

A plug-in is essentially a function that receives a slider instance as its only argument and is initialized during slider startup. You can use the ON and emit functions to do something in the declaration cycle function of the slide.

Extended drag control

If you want to extend the slider drag control, you can issue custom events ksDragStart, ksDrag and ksDragEnd positions, official example.

Implement an H5 round broadcast popover

1. Introduce dependencies

React + TS is used as an example.

import * as React from "react";
import "keen-slider/keen-slider.min.css";
import "./styles.css";
import { useKeenSlider, TrackDetails } from "keen-slider/react";
Copy the code

2. Use useKeenSlider to create an instance

const [details, setDetails] = React.useState<TrackDetails | null> (null);

  const [sliderRef] = useKeenSlider<HTMLDivElement>({
    loop: true.detailsChanged(s) {
      setDetails(s.track.details);
    },
    initial: 2.slides: {
      origin: "center".perView: 2.spacing: 0}});Copy the code

3. Mount sliderRef to a specific DOM

<div
      ref={sliderRef}
      className="keen-slider zoom-out"
      style={{ width: "375px" }}
    >
      {images.map((src, idx) = > (
        <div key={idx} className="keen-slider__slide zoom-out__slide">
          <div style={scaleStyle(idx)}>
            <img src={src} />
          </div>
        </div>
      ))}
    </div>
Copy the code

4. During the sliding process, control the size of the slider

Write a scaleStyle function that goes back in real time during the slide.

function scaleStyle(idx: number) {
    if(! details)return {};
    const slide = details.slides[idx];
    const scale_size = 0.7;
    const scale = 1 - (scale_size - scale_size * slide.portion);
    return {
      transform: `scale(${scale}) `.WebkitTransform: `scale(${scale}) `
    };
  }
Copy the code

5. Online Demo address

The online demo