Files
PC-Light-Forum/simple_scroll.html
A1300399510 aa5a7058ad no message
2025-11-08 22:22:44 +08:00

92 lines
3.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: 1000px; margin: 20px auto; gap: 20px; }
.left, .right { padding: 20px; border-radius: 8px; }
.left { width: 300px; background: #f0f8fb; }
.right { width: 680px; background: #fef7fb; }
.fixed { position: fixed; bottom: 20px; max-height: calc(100vh - 40px); overflow: hidden; z-index: 10; }
</style>
</head>
<body>
<div class="container">
<div class="left" id="left">
<h3>左侧短内容</h3>
<p>这里是左侧内容,相对较短。</p>
<p>当页面滚动时,左侧会先触底。</p>
<p>触底后会固定在底部。</p>
<p>右侧内容可以继续滚动。</p>
</div>
<div class="right" id="right">
<h3>右侧长内容</h3>
<p>右侧内容第1行</p>
<p>右侧内容第2行</p>
<p>右侧内容第3行</p>
<p>右侧内容第4行</p>
<p>右侧内容第5行</p>
<p>右侧内容第6行</p>
<p>右侧内容第7行</p>
<p>右侧内容第8行</p>
<p>右侧内容第9行</p>
<p>右侧内容第10行</p>
<p>右侧内容第11行</p>
<p>右侧内容第12行</p>
<p>右侧内容第13行</p>
<p>右侧内容第14行</p>
<p>右侧内容第15行</p>
</div>
</div>
<script>
// 极其简化的滚动固定实现
window.onload = function() {
const left = document.getElementById('left');
const right = document.getElementById('right');
const container = document.querySelector('.container');
const containerLeft = container.getBoundingClientRect().left;
const containerRight = window.innerWidth - (containerLeft + container.offsetWidth);
let leftFixed = false;
let rightFixed = false;
let scrollTimeout;
// 节流滚动处理
window.onscroll = function() {
if (scrollTimeout) clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(function() {
const windowHeight = window.innerHeight;
const leftRect = left.getBoundingClientRect();
const rightRect = right.getBoundingClientRect();
// 左侧固定逻辑
if (!leftFixed && leftRect.bottom <= windowHeight && leftRect.top <= 0) {
left.classList.add('fixed');
left.style.left = containerLeft + 'px';
leftFixed = true;
} else if (leftFixed && leftRect.top > 0) {
left.classList.remove('fixed');
left.style.left = '';
leftFixed = false;
}
// 右侧固定逻辑
if (!rightFixed && rightRect.bottom <= windowHeight && rightRect.top <= 0) {
right.classList.add('fixed');
right.style.right = containerRight + 'px';
rightFixed = true;
} else if (rightFixed && rightRect.top > 0) {
right.classList.remove('fixed');
right.style.right = '';
rightFixed = false;
}
}, 30);
};
};
</script>
</body>
</html>