如何不借助第三方库实现滚动时区块覆盖效果(类似谷歌广告底部)
实现底部CTA区块覆盖页面内容的方案
纯CSS就能实现,两种方案可选
1. 始终固定在底部的覆盖效果
直接用CSS固定定位就能搞定,不需要任何JS:
/* 页面主体内容(可选:如果不想内容被完全遮挡,加个底部内边距,值等于CTA高度) */ .main-content { /* padding-bottom: 80px; */ } /* 底部CTA区块 */ .bottom-cta { position: fixed; left: 0; bottom: 0; width: 100%; height: 80px; /* 按需调整高度 */ background: #fff; /* 背景色确保能盖住下方内容 */ z-index: 999; /* 保证在所有页面元素之上 */ box-shadow: 0 -2px 10px rgba(0,0,0,0.1); /* 加阴影增强层次感,可选 */ display: flex; align-items: center; justify-content: center; padding: 0 20px; }
对应的HTML结构:
<div class="main-content"> <!-- 页面主体内容 --> </div> <div class="bottom-cta"> <!-- CTA内容,比如按钮、文案 --> <button>立即启动</button> <span>获取定制广告方案</span> </div>
2. 滚动到接近底部才显示的覆盖效果
如果要和目标页面一样,滚动到快到底部时才弹出CTA覆盖内容,纯CSS也能实现,但需要浏览器支持:has()和scroll()伪类(新版本Chrome、Firefox等均支持):
.bottom-cta { position: sticky; bottom: 0; width: 100%; height: 80px; background: #fff; z-index: 999; box-shadow: 0 -2px 10px rgba(0,0,0,0.1); /* 默认隐藏 */ opacity: 0; visibility: hidden; transition: opacity 0.3s, visibility 0.3s; } /* 当页面滚动到距离底部80px以内时,显示CTA */ body:has(.main-content:scroll(near 80px from bottom)) .bottom-cta { opacity: 1; visibility: visible; }
注意:如果需要兼容旧浏览器,这个CSS方案适用性有限,建议用下面的JS方案。
兼容更好的简易JS方案
几行代码就能实现灵活的触发逻辑,兼容性拉满:
const cta = document.querySelector('.bottom-cta'); window.addEventListener('scroll', () => { // 计算当前滚动位置距离页面底部的距离 const distanceToBottom = document.documentElement.scrollHeight - window.innerHeight - window.scrollY; // 距离底部小于100px时显示CTA,否则隐藏 if (distanceToBottom < 100) { cta.classList.add('show'); } else { cta.classList.remove('show'); } });
配套的CSS:
.bottom-cta { position: fixed; left: 0; bottom: 0; width: 100%; height: 80px; background: #fff; z-index: 999; box-shadow: 0 -2px 10px rgba(0,0,0,0.1); /* 默认隐藏在视口外 */ transform: translateY(100%); transition: transform 0.3s ease; } .bottom-cta.show { /* 滑入视口 */ transform: translateY(0); }
HTML结构和之前的一致即可。
内容的提问来源于stack exchange,提问作者Luke Darius
相关产品推荐
相关产品推荐

