首页 > 解决方案 > 如何更好地改变固定元素的位置

问题描述

请检查这个例子。你可以在 Codepen 上更好地看到它。我希望#fixeddiv 不覆盖#bottomdiv。所以我改变了每当即将覆盖的top属性。#fixed#fixed#bottom

但是如果我滚动页面太快,这种情况仍然会出现。你有办法解决吗?感谢您的回答。

图片

document.addEventListener('wheel', changeFixed, false);

function changeFixed() {
  const footToTop = document.getElementById('bottom').getBoundingClientRect().top;
  const viewHeight = window.innerHeight;
  const isButtom = footToTop + 0 < viewHeight;
  document.getElementById('fixed').style.bottom = isButtom ? 100 + 'px' : 30 + 'px';
}
* {
    margin: 0px;
}
#container {
    height: 300vh;
    display: flex;
    align-items: flex-end;
  
}
#fixed {
    transition: top 1s;
    position: fixed;
    left: 10px;
    bottom: 30px;
    width: 100px;
    height: 200px;
    background: red;
}
#bottom {
    width: 100vw;
    height: 50px;
    background: blue;
}
<div id="container">
  <div id="fixed"></div>
  <div id="bottom"></div>
</div>

标签: javascriptjquerycssanimation

解决方案


这个纯 CSS 解决方案如何使用position: sticky

* {
    margin: 0px;
}
#container {
    height: 300vh;
    display: flex;
    align-items: flex-end;
    padding-bottom:10px;
  
}
#fixed {
    
    position: sticky;
    left: 10px;
    bottom: 20px;
    width: 100px;
    height: 200px;
    background: red;
}
#bottom {
    width: 100vw;
    height: 50px;
    background: blue;
}
<div id="container">
  <div id="fixed"></div>
  
</div>
<div id="bottom"></div>


推荐阅读