javascript - 如何更好地改变固定元素的位置
问题描述
请检查这个例子。你可以在 Codepen 上更好地看到它。我希望#fixed
div 不覆盖#bottom
div。所以我改变了每当即将覆盖的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>
解决方案
这个纯 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>
推荐阅读
- java - Flowable 将 bytearray 列加载为 BLOB
- async-await - 如何在 hylang 中编写像点(。)运算符这样的宏?
- sql - 有没有办法在 Oracle SQL 中将数字转换为带圆圈的数字?(1到①或20到⑳)
- concurrency - 使用并发调用从远程服务器检索数据的最佳方式是什么?
- javascript - 使用谷歌 cse 服务时出现错误:403 - ReactJS
- javascript - C#:错误的 DateTime 格式传递给前端
- attributes - 如何在类的所有属性上添加 Xss 属性?
- php - 如何使用基于数组的内爆来分隔多个值或拆分多个值?
- instagram - IG 图形 API:轮播上的视频观看次数
- spotbugs - 排除 LocalDate 类以供 SpotBugs 插件检查