如何更好地改变固定元件的位置

时间:2019-04-02 09:12:25

标签: javascript jquery css css3 animation

请检查this example。您可以在Codepen上更好地看到它。我希望#fixed div不覆盖#bottom div。因此,每当top即将覆盖#fixed时,我都会更改#fixed的{​​{1}}属性。

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

image

#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;
}

3 个答案:

答案 0 :(得分:1)

使用position: sticky的纯CSS解决方案怎么样

* {
    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>

答案 1 :(得分:0)

如何收听“滚动”事件?

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

答案 2 :(得分:0)

我认为您需要知道的是何时滚动到底部。这意味着,如果您已滚动到底部,则知道存在一个bottom div,然后应将fixed div从底部移出50px。像这样的东西

function changeFixed() {
  const documentHeight = document.body.scrollHeight;
  const scrollPosition = window.scrollY;
  const viewHeight = window.innerHeight;
  // documentHeight - (scrollPosition + viewHeight) will be 0 when you have scrolled to bottom.
  if (documentHeight - (scrollPosition + viewHeight) <= 50) {
    document.getElementById('fixed').style.top = "auto";
    document.getElementById('fixed').style.bottom = "50px";
  } else {
    document.getElementById('fixed').style.top = "200px";
    document.getElementById('fixed').style.bottom = "auto";
  }
}

PS:如果要动画,则需要添加适当的过渡。