首页 > 文章列表 > 侧边悬浮按钮随页面滚动而隐现是如何实现的?

侧边悬浮按钮随页面滚动而隐现是如何实现的?

457 2025-03-05

侧边悬浮按钮随页面滚动而隐现是如何实现的?

侧边悬浮按钮随页面滚动而隐现的技术

正如您所看到的,侧边悬浮按钮在页面顶端可见,随着屏幕下滑,这些按钮会逐渐消失。这项技术通过检测元素在屏幕上的显示状态来实现。

实现思路

不需要知道元素的高度,而是通过监听元素出现在屏幕上或消失时,再控制元素的显示或隐藏。

示例代码

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>document</title>
  <style>
    h1 {
      text-align: center;
    }

    .text {
      margin-left: 100px;
    }

    .left {
      position: sticky;
      left: 0;
      top: 10px;
    }

    .end{
      margin-bottom: 100px;
    }
  </style>
</head>
<body>
  <h1>标题</h1>
  <div class="left">
    滚动<br>
    到底<br>
    我就<br>
    不见了
  </div>
  <div class="text">
    ......略.......
  </div>
  <div class="end">
    当你看到我,<br>
    左边的文字就消失
  </div>
  <script>
    (function () {

      const endel = document.queryselector('.end');
      const leftel = document.queryselector('.left');

      const obs = new intersectionobserver((entries, observer) => {

        if(entries[0].isintersecting){
          leftel.style.display = 'none';
        }else{
          leftel.style.display = '';
        }
      }, {
        rootmargin: '0px',
        threshold: 0.1,
      });

      obs.observe(endel);
    })();
  </script>
</body>
</html>

intersectionobserver 的介绍

https://developer.mozilla.org...
来源:1729520280