Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

关于吸顶的问题想请教一下

想实现吸顶的效果,搜索后发现可以使用getBoundingClientRect来实现。但我测试的时候发现当元素到达吸顶的条件后,继续往下滚动,吸顶元素会在static和fixed之间来回切换导致元素一直在闪烁。打印top值会发现一会是正常的top值,一会是0,想请问下是为什么?
以下是代码

  <style>
    p {
      margin: 0;
      height: 47px;
    }
    .fixed {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      z-index: 9;
    }
  </style>
</head>
<body>
<div style="background-color: red; height: 200px;">12312321</div>
<div style="height: 47px">
  <p id="p">吸顶</p>
</div>
<div style="background-color: yellow; height: 2000px;">12312321</div>
<script>
window.addEventListener('scroll', function () {
  const p = document.querySelector('#p');
  const top = p.getBoundingClientRect().top;
  console.log(top)
  if (top < 0) {
    p.classList.add('fixed');
  } else {
    p.classList.remove('fixed');
  }
})
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

getBoundingClientRect是相对视图窗口的.所以你应该获取父元素的top。

const top = p.parentElement.getBoundingClientRect().top;

其实也可以用offsetTop,

if (p.parentElement.offsetTop <= (document.documentElement.scrollTop || document.body.scrollTop)) {
    p.classList.add('fixed');
} else {
    p.classList.remove('fixed');
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...