移动端原生JS如何仅在原购物车按钮离开视口时显示底部购物车按钮
实现方案
实现思路
- 优先使用Intersection Observer API检测元素可见性,相比监听scroll事件性能更好,不会频繁触发重绘,更适合移动端场景
- 监听原有页面内的购物车按钮元素,当它离开可视视口时,激活底部固定的购物车按钮,反之隐藏底部按钮
代码修改步骤
1. HTML修改
在</body>标签前添加底部购物车按钮容器,默认隐藏:
<!-- 底部固定购物车按钮 --> <div class="bottom-cart" id="bottomCart"> <button>Add To cart</button> </div>
2. CSS修改
在原有CSS代码末尾新增底部按钮样式规则:
/* 底部购物车按钮样式 */ .bottom-cart { display: none; position: fixed; bottom: 0; left: 0; width: 100%; background-color: rgb(144, 148, 144); padding: 10px; text-align: center; z-index: 999; } .bottom-cart button { padding: 10px; width: 80vw; font-size: 24px; }
3. JS代码替换
完全替换现有JS代码即可,无需额外监听scroll事件:
// 获取原有购物车容器和底部购物车容器 const originCart = document.querySelector('.sticky'); const bottomCart = document.getElementById('bottomCart'); // 创建交叉观察器 const observer = new IntersectionObserver((entries) => { const entry = entries[0]; if (!entry.isIntersecting) { // 原购物车按钮不可见,显示底部按钮 bottomCart.style.display = 'block'; } else { // 原购物车按钮可见,隐藏底部按钮 bottomCart.style.display = 'none'; } }, { // 触发阈值:0代表只要元素有1px离开视口就触发,设为1代表元素完全离开视口才触发 threshold: 0 }); // 开始监听原购物车元素 observer.observe(originCart);
可选调整说明
如果需要原购物车完全离开视口才显示底部按钮,把IntersectionObserver配置里的threshold参数改为1即可。
内容的提问来源于stack exchange,提问作者Massguy
相关产品推荐
相关产品推荐

