滚动列表导航栏吸顶功能的封装

前言

因为遇到了这个需求,网上找了一圈也没发现好用的插件,于是就自己写了一个,使用方式简便,已经在项目的好几处用到了这个插件,现分享出来。

滚动列表头部吸顶效果

gif1

安装 Installation

npm i sticky-list-headers --save

使用 usage

引入 import

import StickyListHeaders from 'sticky-list-headers'

or

<script src="/node_modules/sticky-list-headers/dist/sticky-list-headers.min.js"></script>
复制代码

使用 use

<body>
<div id="outer-container">
    <div id="inner-container">
        <h1 id="header1">标题1</h1>
        <p>列表文本</p>
        <p>列表文本</p>
        <p>列表文本</p>
        <h1  id="header2">标题2</h1>
        <p>列表文本</p>
        <p>列表文本</p>
        <p>列表文本</p>
        <h1  id="header3">标题3</h1>
        <p>列表文本</p>
        <p>列表文本</p>
        <p>列表文本</p>
        <h1  id="header4">标题4</h1>
        <p>列表文本</p>
        <p>列表文本</p>
        <p>列表文本</p>
        <h1  id="header5">标题5</h1>
        <p>列表文本</p>
        <p>列表文本</p>
        <p>列表文本</p>
        <h1  id="header6">标题6</h1>
        <p>列表文本</p>
        <p>列表文本</p>
    </div>
</div>
<script>
new StickyListHeaders({
    outerContainer: 'outer-container',
    innerContainer: 'inner-container',
    headers: ['header1', 'header2', 'header3', 'header4', 'header5', 'header6']
})
</script>
</body>
复制代码

可以在examples目录查看更多细节

选项 OPTIONS

outerContainer

滚动容器的外层容器,用于占位。

参数:id字符串或者dom元素

innerContainer

滚动容器,通常设置一个固定高度以及overflow属性为auto 或者 scroll

参数:id字符串或者dom元素

headers

需要固定在顶部头部列表

参数:包含头部id或者dom元素的列表 Array<String: id> 或者 Array< DOM >

接口 API

refresh

当滚动容器中的内容发生变动,导致容器高度变化,需要调用此函数重新计算,使吸顶头部适应新的容器高度

示例

let stickyListHeaders = new StickyListHeaders({
    outerContainer: 'outer-container',
    innerContainer: 'inner-container',
    headers: ['header1', 'header2', 'header3', 'header4', 'header5', 'header6']
})

// 当dom改变后
stickyListHeaders.refresh()
复制代码

更多 more

issue star or fork 点这里

猜你喜欢

转载自juejin.im/post/5bebf856e51d451fa2388b81