Sticky-js 自定义元素悬浮固定位置
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
使用方法
引入插件文件
<script src="sticky.min.js"></script>
编写 HTML 代码
<div class="selector">Sticky element</div>
初始化插件
var sticky = new Sticky('.selector');
CommonJS 方式
var Sticky = require('sticky-js');
var sticky = new Sticky('.selector');
通过 [data-sticky-container] 属性将元素固定到指定位置
<div data-sticky-container>
<div class="selector">Sticky element</div>
</div>
完整示例
多个元素通过 data-sticky-container 属性设置固定位置
<div class="row" data-sticky-container>
<div class="medium-2 columns">
<img src="http://placehold.it/250x250" class="sticky" data-margin-top="20" data-sticky-for="1023" data-sticky-class="is-sticky">
</div>
<div class="medium-8 columns">
<h1>Sticky-js</h1>
<p>Lorem ipsum.....</p>
</div>
<div class="medium-2 columns">
<img src="http://placehold.it/250x250" class="sticky" data-margin-top="20" data-sticky-for="1023" data-sticky-class="is-sticky">
</div>
</div>
<script src="sticky.min.js"></script>
<script>
var sticky = new Sticky('.sticky');
</script>
方法函数
更新位置,例如父级元素 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 <span></span> 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 |
相关链接
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论