一、Scroll Snap核心概念
容器属性
- scroll-snap-type
- scroll-padding
- scroll-snap-stop
子项属性
- scroll-snap-align
- scroll-margin
二、横向画廊实现
1. HTML基础结构
<div class="gallery-container">
<div class="gallery-track">
<div class="gallery-item">
<img src="image1.jpg" alt="示例图片1">
</div>
<!-- 更多画廊项目 -->
</div>
</div>
2. 核心CSS样式
.gallery-container {
width: 100%;
overflow-x: auto;
scroll-snap-type: x mandatory;
scroll-behavior: smooth;
-webkit-overflow-scrolling: touch;
}
.gallery-track {
display: flex;
height: 80vh;
gap: 1rem;
}
.gallery-item {
scroll-snap-align: center;
flex: 0 0 90%;
max-width: 90%;
position: relative;
}
@media (min-width: 768px) {
.gallery-item {
flex: 0 0 45%;
max-width: 45%;
}
}
3. 增强交互效果
/* 当前激活项高亮 */
.gallery-item:target {
outline: 3px solid #4CAF50;
}
/* 自定义滚动条 */
.gallery-container::-webkit-scrollbar {
height: 8px;
}
.gallery-container::-webkit-scrollbar-thumb {
background: rgba(0,0,0,0.2);
border-radius: 4px;
}
/* 移动端优化 */
@supports (-webkit-overflow-scrolling: touch) {
.gallery-container {
padding-bottom: 1rem;
}
}
三、高级功能扩展
1. 分页指示器
<div class="gallery-pagination">
<a href="#item1" rel="external nofollow" class="pagination-dot"></a>
<!-- 更多分页点 -->
</div>
<style>
.gallery-pagination {
display: flex;
justify-content: center;
gap: 0.5rem;
margin-top: 1rem;
}
.pagination-dot {
width: 12px;
height: 12px;
border-radius: 50%;
background: #ccc;
}
.pagination-dot:target {
background: #333;
}
</style>
2. 键盘导航支持
document.addEventListener('keydown', (e) => {
const items = document.querySelectorAll('.gallery-item');
const current = document.querySelector('.gallery-item:target');
if (e.key === 'ArrowLeft') {
// 左键逻辑
} else if (e.key === 'ArrowRight') {
// 右键逻辑
}
});
四、性能优化建议
- 图片懒加载:使用loading=”lazy”属性
- GPU加速:will-change: transform
- 触摸优化:-webkit-overflow-scrolling
- 资源预加载:link rel=”preload”