Files
PC-Light-Forum/simple_scroll.html
A1300399510 b7feedb350 no message
2025-11-09 23:34:00 +08:00

131 lines
4.8 KiB
HTML

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>滚动触底固定效果</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
min-height: 200vh;
background: #f8f9fa;
}
.container {
display: flex;
width: 1200px;
margin: 20px auto;
gap: 20px;
}
.left {
width: 200px;
height: 1000px;
background-color: aqua;
}
.right {
flex: 1;
height: 1500px;
background-color: #ff0090;
}
.bottom {
width: 1200px;
height: 200px;
margin: 20px auto;
background-color: #0090ff;
}
</style>
</head>
<body>
<div class="container">
<div class="left" id="left"></div>
<div class="right" id="right"></div>
</div>
<div class="bottom" id="bottom"></div>
<script>
// 获取DOM元素
const left = document.getElementById('left');
const right = document.getElementById('right');
const bottom = document.getElementById('bottom');
const container = document.querySelector('.container');
// 存储初始位置信息
let containerLeft = 0;
let leftWidth = 0;
let rightWidth = 0;
let gap = 20; // 与CSS中的gap一致
// 初始化函数
function init() {
const containerRect = container.getBoundingClientRect();
containerLeft = containerRect.left;
leftWidth = left.offsetWidth;
rightWidth = right.offsetWidth;
}
// 滚动时检查并固定元素
window.addEventListener('scroll', function() {
const scrollY = window.scrollY;
const windowHeight = window.innerHeight;
// 获取底部元素的顶部位置(相对于文档)
const bottomTop = bottom.getBoundingClientRect().top + scrollY;
// 获取左右元素的底部位置(相对于文档)
const leftBottom = left.getBoundingClientRect().bottom + scrollY;
const rightBottom = right.getBoundingClientRect().bottom + scrollY;
// 检查左侧元素是否需要固定
if (leftBottom >= bottomTop && left.style.position !== 'fixed') {
// 固定左侧元素
left.style.position = 'fixed';
left.style.bottom = '0';
left.style.left = containerLeft + 'px';
left.style.width = leftWidth + 'px';
} else if (scrollY < bottomTop - windowHeight && left.style.position === 'fixed') {
// 恢复左侧元素
left.style.position = '';
left.style.bottom = '';
left.style.left = '';
left.style.width = '';
}
// 检查右侧元素是否需要固定
if (rightBottom >= bottomTop && right.style.position !== 'fixed') {
// 固定右侧元素
right.style.position = 'fixed';
right.style.bottom = '0';
right.style.left = (containerLeft + leftWidth + gap) + 'px';
right.style.width = rightWidth + 'px';
} else if (scrollY < bottomTop - windowHeight && right.style.position === 'fixed') {
// 恢复右侧元素
right.style.position = '';
right.style.bottom = '';
right.style.left = '';
right.style.width = '';
}
});
// 窗口大小改变时重新计算位置
window.addEventListener('resize', function() {
init();
// 如果元素已固定,更新它们的位置
if (left.style.position === 'fixed') {
left.style.left = containerLeft + 'px';
}
if (right.style.position === 'fixed') {
right.style.left = (containerLeft + leftWidth + gap) + 'px';
}
});
// 初始化
init();
</script>
</body>
</html>