如何实现垂直滚动时仅单张博客卡片显示,带淡入淡出及固定背景效果
实现方案
你需要的滚动单卡切换效果可以通过CSS滚动捕捉+过渡动画+轻量JS逻辑实现,无需引入额外第三方工具,修改方案如下:
1. 基础布局与滚动配置
首先添加全局样式,实现固定背景、隐藏滚动条、适配滚动逻辑:
/* 全局基础配置 */ * { margin: 0; padding: 0; box-sizing: border-box; } html, body { height: 100vh; overflow-y: scroll; scroll-behavior: smooth; /* 隐藏滚动条 */ scrollbar-width: none; /* 适配Firefox */ } body::-webkit-scrollbar { display: none; /* 适配Chrome、Safari等webkit内核浏览器 */ } /* 固定背景实现视差效果 */ body { background: #000 url(你的背景图地址) center/cover fixed no-repeat; } /* 卡片容器配置 */ .section__posts { height: calc(100vh * var(--card-count)); /* 高度=卡片数量*100vh,3张卡默认就是300vh */ position: relative; padding: 10vh 5vw; }
2. 卡片样式与过渡效果
给卡片添加定位、默认透明状态和过渡动画:
.section__posts--card { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 90%; max-width: 800px; background: #fff; border-radius: 12px; padding: 24px; opacity: 0; visibility: hidden; transition: all 0.6s ease; z-index: 1; } /* 激活状态的卡片可见 */ .section__posts--card.active { opacity: 1; visibility: visible; z-index: 10; } /* 卡片内部样式可按需调整 */ .blog-image { width: 100%; height: 200px; object-fit: cover; border-radius: 8px; margin-bottom: 16px; } .blog-title { font-size: 22px; margin-bottom: 12px; } .blog-overview { margin-bottom: 20px; line-height: 1.6; } .btn { display: inline-block; padding: 8px 20px; background: #222; color: #fff; text-decoration: none; border-radius: 4px; }
3. JS逻辑实现滚动切换
添加以下JS代码,监听滚动事件,根据滚动位置切换激活的卡片:
const cards = document.querySelectorAll('.section__posts--card') const cardCount = cards.length // 给容器设置css变量适配高度 document.querySelector('.section__posts').style.setProperty('--card-count', cardCount) // 监听滚动事件 window.addEventListener('scroll', () => { // 计算当前滚动进度 const scrollTop = window.scrollY const totalHeight = document.body.scrollHeight - window.innerHeight const progress = scrollTop / totalHeight // 根据进度判断当前激活的卡片下标 const activeIndex = Math.min(Math.floor(progress * cardCount), cardCount - 1) // 切换卡片激活状态 cards.forEach((card, index) => { index === activeIndex ? card.classList.add('active') : card.classList.remove('active') }) }) // 页面加载时默认激活第一张卡片 window.dispatchEvent(new Event('scroll'))
以上方案实现了滚动时单张卡片淡入淡出切换、同一时间仅一张可见、背景固定无滚动条的效果,你可以根据需求调整过渡时长、卡片尺寸等参数。
内容的提问来源于stack exchange,提问作者GeraCamoDev
相关产品推荐
相关产品推荐

