h5 实现固定前三榜单
实现固定前三榜单的H5方法
使用CSS的position: sticky属性可以轻松实现固定前三榜单的效果。该方法兼容主流移动浏览器,且无需JavaScript。

<div class="rank-list">
<div class="rank-item rank-top">第一名</div>
<div class="rank-item rank-top">第二名</div>
<div class="rank-item rank-top">第三名</div>
<div class="rank-item">第四名</div>
<!-- 更多排名项 -->
</div>
.rank-list {
height: 100vh;
overflow-y: auto;
}
.rank-top {
position: sticky;
top: 0;
background: #fff;
z-index: 10;
}
.rank-item {
padding: 15px;
border-bottom: 1px solid #eee;
}
使用JavaScript增强交互
如果需要更复杂的交互效果,可以结合JavaScript实现动态固定:

window.addEventListener('scroll', function() {
const topItems = document.querySelectorAll('.rank-top');
const scrollTop = window.scrollY;
if(scrollTop > threshold) {
topItems.forEach(item => {
item.classList.add('fixed');
});
} else {
topItems.forEach(item => {
item.classList.remove('fixed');
});
}
});
.rank-top.fixed {
position: fixed;
top: 0;
width: 100%;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
性能优化建议
避免在滚动事件中使用复杂计算,推荐使用Intersection Observer API替代传统滚动事件监听:
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if(entry.isIntersecting) {
entry.target.classList.add('visible');
} else {
entry.target.classList.remove('visible');
}
});
}, {threshold: 0.1});
document.querySelectorAll('.rank-item').forEach(item => {
observer.observe(item);
});
兼容性处理
对于不支持sticky的老版本浏览器,可以使用polyfill或备用方案:
@supports not (position: sticky) {
.rank-top {
position: relative;
}
/* 备用样式 */
}
