
左右随屏动画实现
问题:页面中的左右按钮会随着页面滑动而出现和消失。
解答:
采用 IntersectionObserver API 来检测页面上某个元素是否出现在屏幕中,从而控制左右按钮的显示和隐藏。
代码范例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>左右随屏动画</title>
<style>
body {
margin: 0;
padding: 0;
}
.container {
display: flex;
}
.left-panel {
background: #ccc;
width: 200px;
height: 100vh;
position: sticky;
left: 0;
top: 0;
}
.right-panel {
flex: 1;
background: #eee;
height: 100vh;
overflow: scroll;
}
.end-marker {
position: absolute;
bottom: 0;
width: 1px;
height: 1px;
}
</style>
</head>
<body>
<div class="container">
<div class="left-panel">
<h1>左侧面板</h1>
</div>
<div class="right-panel">
<h1>右侧面板</h1>
<div style="height: 2000px;"></div>
<div class="end-marker"></div>
</div>
</div>
<script>
const leftPanel = document.querySelector('.left-panel');
const endMarker = document.querySelector('.end-marker');
const observer = new IntersectionObserver((entries, observer) => {
if (entries[0].isIntersecting) {
leftPanel.style.display = 'none';
} else {
leftPanel.style.display = '';
}
});
observer.observe(endMarker);
</script>
</body>
</html>工作原理:
- 使用 IntersectionObserver 创建一个观察器。
- 将观察器绑定到页面底部的一个元素,例如 endMarker。
- 当 endMarker 进入或离开屏幕时,观察器会触发 isIntersecting 回调函数。
- 根据 endMarker 的可见性,显示或隐藏左侧面板。
注意:
- rootMargin 允许指定观察元素周围的额外区域,以在进入或离开屏幕之前触发回调函数。
- threshold 允许指定观察元素可见区域的百分比,以触发回调函数。










