如何实现div固定在屏幕底部,滚动至页尾时上移避让版权区?
实现方法:固定底部div滚动到页面末尾时上移
完全可以实现这个效果,核心思路是用固定定位让div初始贴紧屏幕底部,再通过监听滚动事件判断页面滚动位置,动态调整div的样式来留出版权标识的空间。以下是具体实现方案:
HTML结构
<div class="sticky-bottom-div">我是始终固定在底部的内容</div> <footer class="copyright">© 2024 版权所有</footer>
CSS样式
/* 初始状态:固定在屏幕底部 */ .sticky-bottom-div { position: fixed; bottom: 0; left: 0; width: 100%; padding: 12px; background-color: #f5f5f5; transition: margin-bottom 0.3s ease; /* 添加过渡动画让移动更平滑 */ } /* 滚动到末尾时的状态:上移留出版权空间 */ .sticky-bottom-div.shift-up { margin-bottom: 40px; /* 值等于版权栏的高度 */ } .copyright { height: 40px; background-color: #333; color: #fff; display: flex; align-items: center; justify-content: center; margin-top: 2000px; /* 模拟长页面内容,方便测试滚动效果 */ }
JavaScript逻辑
const stickyDiv = document.querySelector('.sticky-bottom-div'); const copyrightBar = document.querySelector('.copyright'); window.addEventListener('scroll', () => { // 计算当前滚动位置到页面底部的剩余距离 const remainingScroll = document.documentElement.scrollHeight - (window.scrollY + window.innerHeight); // 当剩余距离小于等于版权栏高度时,触发上移样式 if (remainingScroll <= copyrightBar.offsetHeight) { stickyDiv.classList.add('shift-up'); } else { stickyDiv.classList.remove('shift-up'); } });
效果说明
- 页面未滚动到末尾时,
.sticky-bottom-div通过position: fixed牢牢固定在屏幕底部。 - 当滚动到接近页面底部,剩余滚动距离小于等于版权栏高度时,给div添加
shift-up类,通过margin-bottom让它向上移动40px,刚好露出下方的版权标识。 - 滚动离开底部区域后,div会自动移除类名,回到初始贴底状态。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

