Sticky-js 是一个用普通 javascript 编写的 Sticky 元素库。有了这个库,你可以很容易地在你的网站上设置粘性元素。它也很灵敏。
特点
Written in vanilla javascript, no dependencies needed
Lightweight (minified: ~6.08kb, gzipped: ~1.67kb)
It can be sticky to the entire page or to selected parent container
No additional CSS needed
安装
npm install sticky-js
bower install sticky.js
使用方法
引入插件文件
编写 HTML 代码
初始化插件
var sticky = new Sticky('.selector');
CommonJS 方式
var Sticky = require('sticky-js');
var sticky = new Sticky('.selector');
通过 [data-sticky-container] 属性将元素固定到指定位置
完整示例
多个元素通过 data-sticky-container 属性设置固定位置
Sticky-js
Lorem ipsum.....
var sticky = new Sticky('.sticky');
方法函数
更新位置,例如父级元素 data-sticky-container 改变了高度
var sticky = new Sticky('.sticky');
// and when parent change height..
sticky.update();
销毁固定元素的设置
var sticky = new Sticky('.sticky');
sticky.destroy();
可选参数
Option
Type
Default
Description
data-sticky-wrap
boolean
false
When it’s true sticky element is wrapped in which has sticky element dimensions. Prevents content from “jumping”.
data-margin-top
number
0
Margin between page and sticky element when scrolled
data-sticky-for
number
0
Breakpoint which when is bigger than viewport width, sticky is activated and when is smaller, then sticky is destroyed
data-sticky-class
string
null
Class added to sticky element when it is stuck
相关链接