js实现多个标题吸顶效果

2020-01-08

对于导航的吸顶效果,pc端和移动端的需求可能有些差异。在pc端,我们通常只需要一个顶部导航;在移动端,在滑动页面的时候,更需要多个标题的吸顶(例如地区的选择,需要将省份吸顶)。

单个标题吸顶和多个标题吸顶的区别在于:多个标题吸顶需要确定一个高度范围,在这个范围中只能有一个标题吸顶,其他都是固定效果。

一、页面布局及样式

此处为了测试效果,用了几个重复的section标签,大家根据实际需求编写布局和样式。

<body>
 <ul id="container">
 <h1>实现多个标题的吸顶</h1>
 <section>
  <div class="box">header1</div>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
 </section>
 
 <!--设置多个如header1的子列表,窗口可以进行滚动,此处省略-->
 
 <section>
  <div class="box">header5</div>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
 </section>
 
 </ul>
</body>
<style type="text/css">
 * {
 padding: 0;
 margin: 0;
 }
 ul {
 width: 100%;
 }
 li {
 width: 200px;
 color: white;
 margin: 10px;
 list-style: none;
 border-radius: 5px;
 border: 1px solid #191970;
 background: #4169E1;
 text-align: center;
 }
 div {
 width: 100%;
 height: 30px;
 color: white;
 padding-left: 20px;
 background: #DC143C;
 }
 .box1 {
 position: fixed;
 top: 0;
 }
</style>

二、js的编写

1、获取所有需要吸顶效果的标题。这里的标题最好用相同的布局和样式,获取时能够更快捷和统一。

var box = document.getElementsByClassName('box'), //获取所有需要吸顶效果的标题
  section = document.getElementsByTagName('section'); //获取所有子列表,后面有用

2、获取标题个数和定义一个数组,用来存放每个标题到父元素的距离(offsetTop)。

var ot = [],  //存储每个标题的offsetTop
  len = box.length;   //标题的个数

3、遍历所有标题,获取offsetTop,并存入ot数组中。

for(let i=0; i<len; i++) {
 ot.push(box[i].offsetTop);  //获取每个标题的offsetTop
}

4、监听window的滚动事件,获取scrollTop;如果滚动高度位于第i个标题的offsetTop和第i+1个标题的offsetTop之间(例如滚动的高度位于header1和header2的offsetTop之间,heade1吸顶),则第i个标题添加box1样式,实现吸顶。

window.onscroll = function () {
 //获取滚动的高度
 var st = document.documentElement.scrollTop || document.body.scrollTop;
 
 for(let i=0; i<len; i++) {
 if(st>ot[i] && st<ot[i+1]) { //滚动时监听位置,为标题的吸顶设置一个现实范围
  box[i].className = 'box box1';
 } else {
  box[i].className = 'box';
 }
 
 }
}

5、第四步中,有个问题:当滚动道最后一个标题(i)时,无法获取(i+1)。

解决方法:从第一步中获得的section标签集合中拿出最后一个子列表(section[0]),然后获取最后一个子列表的高度,计算出最后一个标题的显示高度范围,并存入ot数组中。

//获取最后一个子列表的高度,为了设置最后一个吸顶标题的位置
//section[len-1].getBoundingClientRect().height
//此方法返回一个number
 
ot.push(box[len-1].offsetTop + section[len-1].getBoundingClientRect().height);

三、最后效果

完整js代码

var box = document.getElementsByClassName('box'), //获取所有需要吸顶效果的标题
 section = document.getElementsByTagName('section'); //获取所有子列表
 
var ot = [],       //存储每个标题的offsetTop
 len = box.length;   //标题的个数
 
for(let i=0; i<len; i++) {
 ot.push(box[i].offsetTop);  //获取每个标题的offsetTop
}
 
//获取最后一个子列表的高度,为了设置最后一个吸顶标题的位置
//section[len-1].getBoundingClientRect().height
//此方法返回一个number
 
ot.push(box[len-1].offsetTop + section[len-1].getBoundingClientRect().height);
 
window.onscroll = function () {
 //获取滚动的高度
 var st = document.documentElement.scrollTop || document.body.scrollTop;
 
 for(let i=0; i<len; i++) {
 if(st>ot[i] && st<ot[i+1]) { //滚动时监听位置,为标题的吸顶设置一个现实范围
  box[i].className = 'box box1';
 } else {
  box[i].className = 'box';
 }
 
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持北冥有鱼。

《js实现多个标题吸顶效果.doc》

下载本文的Word格式文档,以方便收藏与打印。