【原生js面试题】原生js实现吸顶效果

更新时间:2021-07-21    来源:js教程    手机版     字体:

【www.bbyears.com--js教程】

实现思路如下:

1. div初始居普通文档流中

2. 给window添加scroll事件(可事件节流),获取div的offset的top值,滚动时scrollTop值和top比较,当到达top时给div添加一个fixed的class使其固定

3. 向上滚动时当到达div初始top时则删除fixed的class,此时div又回到普通文档流中

4. fixed样式非IE6浏览器使用position:fixed,IE6使用position:absolute和IE expression

效果图:

代码如下:

 

 代码如下

 

 无标题文档

 

 <script>

  window.onload = function() {

   var oDiv = document.getElementById('div1');

   var divT = oDiv.offsetTop;

   //console.log(divT);

   window.onscroll = function() {

    // 获取当前页面的滚动条纵坐标位置 (依次为火狐谷歌、safari、IE678)

    var scrollT = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;

    if (scrollT >= divT) {

     if (window.navigator.userAgent.indexOf('MSIE 6.0') != -1) {

      // 兼容IE6代码

      oDiv.style.position = 'absolute';

      oDiv.style.top = scrollT + 'px';

      oDiv.style.left = 0 + 'px';

     } else {

      // 正常浏览器代码

      oDiv.style.position = 'fixed';

      oDiv.style.top = 0;

      oDiv.style.left = 0;

     }

    } else

     oDiv.style.position = '';

   }

  }

 </script>

 

  以上

  以上

  以上

  以上

  以上

  以上

  以上

  

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

  啦啦啦啦啦

 

 

本文来源:http://www.bbyears.com/wangyezhizuo/131116.html

热门标签

更多>>

本类排行