@zhinan-oppo/sticky
v3.30.1
Published
A library to handle sticky position
Downloads
5
Readme
sticky
Install
使用 yarn 安装
yarn add @zhinan-oppo/sticky引用方式
import { initStickyElement, initAllBySelector } from '@zhinan-oppo/sticky';接口
initStickyElement(element, options)- 参数
element是需要被设置为黏性布局的HTMLElement - 参数
options是可选的object,包含以下属性container: 可选,默认为element.offsetParent- 如果
container未指定且element.offsetParent为null,会报错,具体参见:offsetParent
- 如果
scrollHandlers: 可选,传递给scrollHandle的回调函数,具体参见:scrollHandle
- 参数
initAllBySelector(selector, root)- 参数
selector是可选的字符串,传递给root.querySelectorAll,所有被选中的 element 会逐一传入到initStickyElement中以默认参数初始化 - 参数
root是可选的 DOM 节点,默认为window.document
- 参数
Instruction (Examples)
sticky 布局
粘性布局的 JS 实现方法。sticky-container 为布局容器,sticky-item 为具体的粘性元素。
向下滚动时:
当 sticky-container 的上边界触碰到屏幕顶部,sticky-item 变为 fixed,表现为粘在屏幕上
当 sticky-item 的底部和 sticky-container 的底部贴在一起时,sticky-item 变为 absolute,随 sticky-container 正常滚走。
initStickyItem:手动初始化.sticky-item
<div class="sticky-container" style="position: relative">
<div class="sticky-item" id="sticky">
</div>
</div>const element = document.getElementById('sticky');
initStickyItem(element, {
// scrollHandlers 实际上是监听在 container 上的
scrollHandlers = {
always: (dom, distance, total) => {},
},
});
initStickyItem(element, {
container = element.offsetParent,
scrollHandlers = {
always: (dom, distance, total) => {},
},
});initAllBySelector: 将所有 class 列表中带sticky-item的元素都设置为黏性布局
<div class="sticky-container" style="position: relative">
<div class="sticky-item">
</div>
</div>import { initAllBySelector } from '@zhinan-oppo/sticky';
document.addEventListener('DOMContentLoaded', event => {
initAllBySelector('.sticky-item');
});