模块固顶和固底的一种实现方法—Api(Element.getBoundClientRect())

页面固顶和固底的一种实现方式

引:在 pc web 开发的过程中,经常会遇到一些模块固定的需求,接下来介绍一种固定的方式,通过 Element.getBoundClientRect() Api 来实现。

开发过程中需要获取页面元素的位置,可以参考 用Javascript获取页面元素的位置 这篇文章。

具体的效果 Demo,可以查看这个 git 仓库

效果展示 看这里。

现在把代码贴出来分析一下:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <style>
    #container {
      height: 3000px;
      width: auto;
    }
    #foo {
      margin-top: 200px;
      float: right;
      height: 1200px;
      width: 500px;
      background-color: #777;
      display: block;
      border-bottom: red 10px solid;
      border-top: yellow 10px solid;
    }
    .rightWrap {
      float: right;
      width: 500px;
    }   
  </style>
</head>

<body>
  <div id="container">    
    <div class="rightWrap">
      <div id="foo">来固定我吧</div>
    </div>
  </div>

  <script type="text/javascript">
    
    let fixDiv = document.querySelector('#foo');
    let viewHeight = document.documentElement.clientHeight;
    let bodyScrollHeight = document.body.scrollTop;
    let fixDivBottom = bodyScrollHeight + fixDiv.getBoundingClientRect().bottom;
    let fixDivTop = bodyScrollHeight + fixDiv.getBoundingClientRect().top;
    let dis = fixDivBottom - viewHeight;

    let winScroll = (e) => {

      bodyScrollHeight = document.body.scrollTop;

      if (dis > 0) {
        if (bodyScrollHeight > dis) {
          fixDiv.style.position = "fixed";
          fixDiv.style.top = -dis + "px";
        } else {
          fixDiv.style.position = "static";
          fixDiv.style.top = null;
        }
      } else {
        if(bodyScrollHeight > fixDivTop){
          fixDiv.style.position = "fixed";
          fixDiv.style.top = -fixDivTop + "px";
        }else{
          fixDiv.style.position = "static";
          fixDiv.style.top = null;
        }
      }
    }

    window.addEventListener('scroll', winScroll);
  </script>
</body>

</html>

id 为 foo 的元素就是我们要固定的元素。变量解析:

viewHeight //视窗高度
bodyScrollHeight //页面滚动高度
fixDivBottom //固定元素底边距页面顶端的距离(注意:是页面顶端)
fixDivTop //固定元素顶部距页面顶端的距离(注意:是页面顶端)
dis //fixDivBottom 与 viewHeight 的差值

fixDiv.getBoundingClientRect().bottom  fixDiv.getBoundingClientRect().top 取到的值,都是相对于视窗的,所以要取到距离页面顶端的距离,就要都加上页面的滚动高度bodyScrollHeight

接下来的情况就分为两种了,一种是 dis 大于 0,即被固定的元素超出视窗范围,这个时候我们需要固底了,另一种情况就是没有超出视窗范围,这个时候可以固顶了。

整个代码实现还是很简单的,主要是理清这几个变量的关系就可以了。希望可以用的到。

猜你喜欢

转载自blog.csdn.net/tangxiaolang101/article/details/77747238