likes
comments
collection
share

滑动头部固定,要不也了解下?

作者站长头像
站长
· 阅读数 5

前言

最近公司事情比较少,正好早上有人问我那个滑动粘着头部不动的怎么实现,我想了半天,前几天刚刚写过,那就记录一下咯。于是,女朋友送了我一张图滑动头部固定,要不也了解下?

抛思路

其实思路还蛮简单的,监听容器div的滚动时间,及每个需要fixed的高度,滑到这个对应高度了,fixed住就行了。可能有点笼统,我们结合代码说吧。今天我们从基本的template-script-style模式来贴代码好了

滑动头部固定,要不也了解下?

template

<!--滑动的容器--><div class="scroll-div">    <!--一个头部加一个item的容器-->    <div class="for-class" v-for="item in baseArray">        <!--需要fixed住的头部,id为获取具体位置使用,可替换成ref        绑定class实现添加fixed样式作用-->        <div class="info-line"             :id="item.idName"             :class="{fiexd_line:fiexdItem===item.fiexdItem}">             {{item.name}}        </div>     <!--下方的item,这里与本文关系不到,可忽略-->     <div class="detail-container"           :class="{margin_top:fiexdItem===1000}">          <div class="detail-item"               v-for="sub_item in item.list"               @click="setLocation(sub_item)">               {{sub_item}}          </div>    </div></div>

style

然后是css部分,这里用了scss的写法,具体是什么,自行百度或谷歌,其中只列出了有关的样式,剩余部分用…省略

.scroll-div {      width100%;      overflow: auto;      ...    }    .info-line {     ...     //这个都不是特别重要    }    .fiexd_line {      position: fixed;      width100%;      ...    }

script

重头戏来了,我们一步一步顺清楚。1.数据初始化2.事件监听3.逻辑判断

数据初始化
具体的数据可根据实际情况修改,这里的数据以效果图为准//添加A-Z数组let baseAtoZArray = [];//生成A-Z的字母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`base-line`,    fiexdItem1000,    list: [this.location],},{    name'热门城市',    idName`hot-line`,    fiexdItem100,    listthis.$config.HOT_CITIES,},...this.baseArray];
事件监听+逻辑判断
//监听滚动事件//界面加载完成后,将每一层header距离头部的距离记录下来for (let item of that.baseArray) {    item.top = $('#' + item.idName).offset().top}$('.scroll-div').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,欢迎大佬们猛戳,不定时更新