前言
最近公司事情比较少, 正好早上有人问我那个滑动粘着头部不动的怎么实现, 我想了半天, 前几天刚刚写过, 那就记录一下咯. 于是, 女朋友送了我一张图
抛思路
其实思路还蛮简单的, 监听容器 div 的滚动时间, 及每个需要 fixed 的高度, 滑到这个对应高度了, fixed 住就行了. 可能有点笼统, 我们结合代码说吧.
今天我们从基本的 templatescriptstyle 模式来贴代码好了
[图片上传失败...(image444c6e1536305058022)]
- template
- <! 滑动的容器 >
- <div class="scrolldiv">
- <! 一个头部加一个 item 的容器 >
- <div class="forclass" vfor="item in baseArray">
<! 需要 fixed 住的头部, id 为获取具体位置使用, 可替换成 ref
绑定 class 实现添加 fixed 样式作用 >
- <div class="infoline"
- :id="item.idName"
- :class="{fiexdline:fiexdItem===item.fiexdItem}">
- {{item.name}}
- </div>
- <! 下方的 item, 这里与本文关系不到, 可忽略 >
- <div class="detailcontainer"
- :class="{margintop:fiexdItem===1000}">
- <div class="detailitem"
- vfor="subitem in item.list"
- click="setLocation(subitem)">
- {{subitem}}
- </div>
- </div>
- </div>
- style
然后是 CSS 部分, 这里用了 scss 的写法, 具体是什么, 自行百度或谷歌, 其中只列出了有关的样式, 剩余部分用... 省略
- .scrolldiv {
- width: 100%;
- overflow: auto;
- ...
- }
- .infoline {
- ...
- // 这个都不是特别重要
- }
- .fiexdline {
- position: fixed;
- width: 100%;
- ...
- }
- script
重头戏来了, 我们一步一步顺清楚.
1. 数据初始化
2. 事件监听
3. 逻辑判断
数据初始化
具体的数据可根据实际情况修改, 这里的数据以效果图为准
- // 添加 AZ 数组
- let baseAtoZArray = [];// 生成 AZ 的字母
- for (let i = 65; i <91; i++) {
- baseAtoZArray.push(String.fromCharCode(i));
- }
- // 均分数组并添加相应的数据, 每个子数组最多有 7 个元素
- this.baseArray = [...chunk(baseAtoZArray, 7)];
- for (let item of this.baseArray) {
- this.baseArray[this.baseArray.indexOf(item)] = {
- name: item.join(''),// 显示的文本
- idName: `${item[0]}2${item[item.length 1]}line`,// 唯一 id,es6 模版字符串和下方的... 运算符了解下
- fiexdItem: this.baseArray.indexOf(item),//fixed 标识
- list: this.getRegList(item[0], item[item.length 1]),// 符合该条件的下方内容, 与本文关系不大
- };
- }
- // 添加期望工作城市与热门城市
- this.baseArray = [
- {
- name: '期望工作城市',
- idName: `baseline`,
- fiexdItem: 1000,
- list: [this.location],
- },
- {
- name: '热门城市',
- idName: `hotline`,
- fiexdItem: 100,
- list: this.$config.HOTCITIES,
- },...this.baseArray];
事件监听 + 逻辑判断
- // 监听滚动事件
- // 界面加载完成后, 将每一层 header 距离头部的距离记录下来
- for (let item of that.baseArray) {
- item.top = $('#' + item.idName).offset().top
- }
- $('.scrolldiv').on('scroll', function () {
- // 对每一项数据监测
- for (let item of that.baseArray) {
- if (this.scrollTop> item.top 20) {
- // 因为在同一高度中, 只可能有一个 header, 所以设置一个, 其他 header 不匹配, 然后 duang 的一下符合条件的就 fixed 住了
- that.fiexdItem = item.fiexdItem;
- }
- }
- });
代码就这么多, 主要是数据准备上以及获取上要下点功夫, 还有很多需要优化的地方, 骚年们加油吧, 在这里我就给你们喊:
效果图
后话
最近产出有点多, 希望能对大家有所帮助
好了, 要被老板拖过去搬砖了, 下次见, 有空点点 github 嘛.
这是我的 github, 欢迎大佬们猛戳, 不定时更新 https://github.com/qianbin01
来源: http://www.qdfuns.com/article/51005/ff7323a6c5a7d89232cd177432e7105d.html