API Reference

API 參考

Complete reference for the DriftSlider constructor, options, properties, methods, and events.

DriftSlider 建構函式、選項、屬性、方法和事件的完整參考。

Constructor

建構函式

Create a new DriftSlider instance by passing a target element and an optional configuration object.

傳入目標元素和可選的設定物件來建立新的 DriftSlider 實例。

js
new DriftSlider(el: string | HTMLElement, options?: DriftSliderOptions)
ParameterTypeDefaultDescription
el string | HTMLElement CSS selector string or a direct HTMLElement reference to the slider container.
options DriftSliderOptions {} Optional configuration object. All options listed below can be passed here.
js
// Using a CSS selector
const slider = new DriftSlider('.drift-slider', {
  slidesPerView: 3,
  spaceBetween: 16,
  loop: true,
});

// Using an HTMLElement
const el = document.getElementById('my-slider');
const slider = new DriftSlider(el, { speed: 600 });

Core Options

核心選項

Primary configuration options that control the slider's layout and behavior.

控制滑塊佈局和行為的主要設定選項。

ParameterTypeDefaultDescription
direction 'horizontal' | 'vertical' 'horizontal' Slider direction.
slidesPerView number 1 Number of slides visible at the same time.
spaceBetween number 0 Gap between slides in pixels.
centeredSlides boolean false Center the active slide within the viewport.
slidesPerGroup number 1 Number of slides to advance per swipe or navigation action.
speed number 400 Transition speed in milliseconds.
easing string 'ease-out' CSS easing function for transitions.
loop boolean false Enable infinite loop mode by cloning slides.
loopAdditionalSlides number 0 Number of extra clone slides to append for smoother looping.
initialSlide number 0 Zero-based index of the starting slide.
grabCursor boolean false Show a grab cursor when hovering over the slider.
watchOverflow boolean true Automatically lock the slider when there are not enough slides to scroll.
effect 'slide' | 'fade' | 'coverflow' | 'cards' 'slide' Transition effect. Requires the corresponding effect module.
modules DriftSliderModule[] [] Array of modules to register (e.g. Navigation, Pagination, Autoplay).

Physics Options

物理引擎選項

Fine-tune the physics engine that powers touch/drag interactions. These values control how the slider feels when swiped.

微調驅動觸控/拖曳互動的物理引擎。這些數值控制滑動時的手感。

ParameterTypeDefaultDescription
physics.friction number 0.92 Velocity damping factor (0–1). Higher values keep momentum longer.
physics.attraction number 0.025 Pull force toward the nearest snap point. Higher values snap faster.
physics.bounceRate number 0.5 Spring bounce intensity when reaching edges.

Touch Options

觸控選項

Control how the slider responds to touch and pointer input.

控制滑塊如何回應觸控和指標輸入。

ParameterTypeDefaultDescription
touchEnabled boolean true Enable touch and mouse drag interaction.
threshold number 5 Minimum drag distance in pixels before the slider starts moving.
touchAngle number 45 Maximum angle (in degrees) from the horizontal axis to accept as a swipe.
shortSwipes boolean true Enable short, quick swipe gestures to advance slides.
longSwipesRatio number 0.5 Ratio of the slider width that must be dragged to trigger a long swipe transition.
followFinger boolean true Slider follows finger/pointer movement in real time.
resistance boolean true Enable edge resistance when dragging past the first or last slide.
resistanceRatio number 0.85 Edge resistance strength. Lower values create stronger resistance.

CSS Classes

CSS 類別

Override the default CSS class names used by DriftSlider. Useful when integrating with existing CSS frameworks or naming conventions.

覆蓋 DriftSlider 使用的預設 CSS 類別名稱。在整合現有 CSS 框架或命名慣例時很有用。

ParameterTypeDefaultDescription
containerClass string 'drift-slider' Class applied to the container element.
trackClass string 'drift-track' Class applied to the track element.
listClass string 'drift-list' Class applied to the list element.
slideClass string 'drift-slide' Class applied to each slide element.
slideActiveClass string 'drift-slide--active' Class applied to the currently active slide.
slidePrevClass string 'drift-slide--prev' Class applied to the slide immediately before the active slide.
slideNextClass string 'drift-slide--next' Class applied to the slide immediately after the active slide.
slideVisibleClass string 'drift-slide--visible' Class applied to all slides currently visible in the viewport.
slideCloneClass string 'drift-slide--clone' Class applied to cloned slides in loop mode.

Properties

屬性

Read-only properties available on a DriftSlider instance after initialization.

DriftSlider 實例初始化後可用的唯讀屬性。

PropertyTypeDescription
el HTMLElement The container element the slider was initialized on.
trackEl HTMLElement The track element that wraps the slide list.
listEl HTMLElement The list element that contains all slides.
slides HTMLElement[] Array of all slide elements (including clones in loop mode).
params DriftSliderOptions The current resolved parameters (merged defaults + user options + breakpoint overrides).
activeIndex number Index of the currently active slide.
realIndex number Real slide index, accounting for loop clones.
previousIndex number Index of the previously active slide.
progress number Overall slider progress from 0 (beginning) to 1 (end).
isBeginning boolean Whether the slider is at the first slide.
isEnd boolean Whether the slider is at the last slide.
isLocked boolean Whether the slider is locked due to insufficient slides (watchOverflow).
animating boolean Whether the slider is currently animating a transition.
translate number Current CSS translate value in pixels.
snapGrid number[] Array of snap positions the slider locks to.
slidesGrid number[] Array of slide position offsets.
containerSize number Container width (horizontal) or height (vertical) in pixels.
slideSize number Computed size of a single slide in pixels.
maxTranslate number Maximum translate value (usually 0).
minTranslate number Minimum translate value (negative, furthest scroll position).
destroyed boolean Whether the slider instance has been destroyed.
id string Unique identifier for this slider instance.

Methods

方法

Public methods available on a DriftSlider instance. Methods that return DriftSlider are chainable.

DriftSlider 實例上可用的公開方法。回傳 DriftSlider 的方法可鏈式呼叫。

MethodReturnDescription
slideTo(index, speed?, runCallbacks?) DriftSlider Slide to a specific index. Optional speed overrides the default transition duration. Set runCallbacks to false to suppress events.
slideNext(speed?, runCallbacks?) DriftSlider Advance to the next slide (or group of slides).
slidePrev(speed?, runCallbacks?) DriftSlider Go back to the previous slide (or group of slides).
slideToClosest(speed?) DriftSlider Snap to the closest snap point from the current translate position.
update() void Recalculate all layout values (sizes, grids, snap points). Call after dynamically adding or removing slides.
destroy(cleanStyles?) void Destroy the slider instance, remove event listeners and classes. Pass true to also remove inline styles.
enable() void Re-enable a previously disabled slider.
disable() void Disable the slider (prevents touch/drag and navigation).
on(event, handler) DriftSlider Register an event listener. Returns the slider instance for chaining.
once(event, handler) DriftSlider Register a one-time event listener that is removed after its first invocation.
off(event, handler?) DriftSlider Remove an event listener. If no handler is provided, all listeners for that event are removed.
emit(event, ...args) DriftSlider Manually emit a custom event with optional arguments.
js
const slider = new DriftSlider('.drift-slider', {
  slidesPerView: 3,
  loop: true,
});

// Chainable navigation
slider.slideNext().on('slideChange', (s) => {
  console.log('Now at slide:', s.activeIndex);
});

// Destroy and clean up
slider.destroy(true);

Events

事件

DriftSlider emits lifecycle and interaction events. Listen via the on option at init time or via the .on() method after initialization.

DriftSlider 會發出生命週期和互動事件。透過初始化時的 on 選項或初始化後的 .on() 方法來監聽。

EventArgumentsDescription
init (slider) Fired after the slider is fully initialized.
destroy (slider) Fired after the slider is destroyed.
beforeDestroy (slider) Fired before the destroy process begins.
slideChange (slider) Fired when the active slide index changes.
slideChangeTransitionStart (slider) Fired when a slide change transition animation starts.
slideChangeTransitionEnd (slider) Fired when a slide change transition animation completes.
touchStart (slider, event) Fired on touch/mouse down.
touchMove (slider, event) Fired on touch/mouse move while dragging.
touchEnd (slider, event) Fired on touch/mouse up.
progress (slider, progress) Fired whenever the overall progress value updates (0 to 1).
reachBeginning (slider) Fired when the slider reaches the first slide.
reachEnd (slider) Fired when the slider reaches the last slide.
resize (slider) Fired when the window is resized and the slider recalculates.
breakpoint (slider, breakpoint) Fired when the active breakpoint changes.
setTranslate (slider, translate) Fired whenever the translate value is set.
setTransition (slider, duration) Fired whenever the transition duration is set.
update (slider) Fired after the slider layout is recalculated via update().
autoplayStart (slider) Fired when autoplay begins.
autoplayStop (slider) Fired when autoplay is stopped.
autoplayPause (slider) Fired when autoplay is paused (e.g. on hover).
autoplayResume (slider) Fired when autoplay resumes after a pause.
js
// Listen via the `on` option at init
const slider = new DriftSlider('.drift-slider', {
  on: {
    init: (s) => console.log('Initialized!'),
    slideChange: (s) => console.log('Slide:', s.activeIndex),
  },
});

// Or add listeners after init
slider.on('progress', (s, p) => {
  console.log('Progress:', Math.round(p * 100) + '%');
});

Breakpoints

斷點

The breakpoint system lets you define responsive overrides that apply at specific viewport widths. Breakpoints use a mobile-first approach: each key is a min-width value in pixels, and its options override the base configuration when the viewport is at least that wide.

斷點系統讓你定義在特定視窗寬度套用的響應式覆蓋設定。斷點採用行動優先策略:每個鍵值是以像素為單位的 min-width 值,當視窗至少達到該寬度時,其選項會覆蓋基礎設定。

The following options can be overridden inside a breakpoint:

以下選項可在斷點內覆蓋:

  • slidesPerView
  • spaceBetween
  • slidesPerGroup
  • centeredSlides
  • loop
  • speed
  • grabCursor
js
new DriftSlider('.drift-slider', {
  slidesPerView: 1,
  spaceBetween: 16,
  breakpoints: {
    // when viewport >= 768px
    768: {
      slidesPerView: 2,
      spaceBetween: 20,
    },
    // when viewport >= 1024px
    1024: {
      slidesPerView: 3,
      spaceBetween: 24,
    },
  },
});

When the viewport width crosses a breakpoint boundary, the slider automatically recalculates its layout and emits the breakpoint event with the new breakpoint value.

當視窗寬度跨過斷點邊界時,滑塊會自動重新計算佈局並發出帶有新斷點值的 breakpoint 事件。

js
slider.on('breakpoint', (s, bp) => {
  console.log('Breakpoint changed to:', bp);
  console.log('Slides per view:', s.params.slidesPerView);
});