如何实现仅在kssite-home-intro-sec区块内固定显示底部跳转箭头按钮
实现方案
方案一:纯CSS sticky 定位(优先推荐,无需JS)
position: sticky 定位的元素只会在其父元素的可视范围内生效,父元素滚动出视口后箭头会自动跟随隐藏,刚好匹配你的需求,调整CSS即可:
.kssite-home-intro-sec { background-repeat: no-repeat; background-size: cover; margin-bottom: 100px; background-position: center center; z-index: 1; position: relative; /* 如果不是必须保留,建议删除overflow: hidden避免sticky失效 */ /* overflow: hidden; */ } .arrow-to-next-sec{ /* 把fixed改成sticky */ position: sticky; bottom: 20px; /* 距离视口底部的距离,可自行调整 */ /* 水平居中 */ margin: 0 auto; width: fit-content; cursor: pointer; color: #ffffff; z-index: 99; } .arrow-to-next-sec a{ color: #ffffff; }
注意:如果父元素必须保留
overflow: hidden属性,sticky定位会失效,可选择下面的JS方案。
方案二:Intersection Observer API(性能最优的JS方案)
不需要频繁监听滚动事件,异步触发性能更好:
第一步:新增CSS隐藏状态类
/* 新增隐藏状态类 */ .arrow-to-next-sec.arrow-hidden { opacity: 0; visibility: hidden; transition: opacity 0.3s ease, visibility 0.3s ease; }
第二步:添加JS代码
const introSec = document.querySelector('.kssite-home-intro-sec'); const arrow = document.querySelector('.arrow-to-next-sec'); const observer = new IntersectionObserver((entries) => { entries.forEach(entry => { entry.isIntersecting ? arrow.classList.remove('arrow-hidden') : arrow.classList.add('arrow-hidden'); }); }, { threshold: 0 }); observer.observe(introSec);
方案三:兼容旧浏览器的滚动监听方案
如果需要兼容IE等老旧浏览器,可以用监听scroll事件的方式实现:
const introSec = document.querySelector('.kssite-home-intro-sec'); const arrow = document.querySelector('.arrow-to-next-sec'); function toggleArrow() { const secBottom = introSec.offsetTop + introSec.offsetHeight; const scrollPos = window.scrollY + window.innerHeight; scrollPos > 0 && scrollPos < secBottom ? arrow.classList.remove('arrow-hidden') : arrow.classList.add('arrow-hidden'); } window.addEventListener('load', toggleArrow); window.addEventListener('scroll', toggleArrow);
内容的提问来源于stack exchange,提问作者Aayush Dahal
相关产品推荐
相关产品推荐

