js实现选中缩略图
实现选中缩略图的基本思路
通过监听缩略图的点击事件,动态切换选中状态样式,通常结合高亮边框或透明度变化来区分选中与未选中状态。核心逻辑包括DOM操作、事件监听和样式切换。
HTML结构示例
<div class="thumbnail-container">
<img src="thumb1.jpg" class="thumbnail" data-index="0">
<img src="thumb2.jpg" class="thumbnail" data-index="1">
<img src="thumb3.jpg" class="thumbnail" data-index="2">
</div>
CSS样式准备
.thumbnail {
width: 100px;
height: 100px;
margin: 5px;
cursor: pointer;
border: 2px solid transparent;
transition: border-color 0.3s;
}
.thumbnail.selected {
border-color: #007bff;
opacity: 0.8;
}
JavaScript实现方案
方案一:基础事件监听
document.querySelectorAll('.thumbnail').forEach(thumb => {
thumb.addEventListener('click', function() {
// 移除所有缩略图的选中状态
document.querySelectorAll('.thumbnail').forEach(t => {
t.classList.remove('selected');
});
// 为当前点击的缩略图添加选中状态
this.classList.add('selected');
});
});
方案二:事件委托优化
document.querySelector('.thumbnail-container').addEventListener('click', (e) => {
if (e.target.classList.contains('thumbnail')) {
document.querySelectorAll('.thumbnail').forEach(t => {
t.classList.remove('selected');
});
e.target.classList.add('selected');
}
});
方案三:带数据索引的扩展
let currentSelectedIndex = null;
document.querySelector('.thumbnail-container').addEventListener('click', (e) => {
const thumb = e.target.closest('.thumbnail');
if (!thumb) return;
const index = thumb.dataset.index;
if (currentSelectedIndex !== index) {
document.querySelector(`.thumbnail[data-index="${currentSelectedIndex}"]`)
?.classList.remove('selected');
thumb.classList.add('selected');
currentSelectedIndex = index;
}
});
高级功能实现
缩略图与主图联动
const mainImage = document.getElementById('main-image');
document.querySelector('.thumbnail-container').addEventListener('click', (e) => {
const thumb = e.target.closest('.thumbnail');
if (!thumb) return;
document.querySelectorAll('.thumbnail').forEach(t => {
t.classList.remove('selected');
});
thumb.classList.add('selected');
// 同步更新主图
mainImage.src = thumb.src.replace('thumb', 'large');
});
键盘导航支持
document.addEventListener('keydown', (e) => {
if (!['ArrowLeft', 'ArrowRight'].includes(e.key)) return;
const thumbs = document.querySelectorAll('.thumbnail');
const currentIndex = Array.from(thumbs).findIndex(t =>
t.classList.contains('selected')
);
let newIndex = currentIndex;
if (e.key === 'ArrowLeft') newIndex = Math.max(0, currentIndex - 1);
if (e.key === 'ArrowRight') newIndex = Math.min(thumbs.length - 1, currentIndex + 1);
if (newIndex !== currentIndex) {
thumbs[currentIndex]?.classList.remove('selected');
thumbs[newIndex].classList.add('selected');
thumbs[newIndex].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
});
性能优化建议
使用事件委托替代单独的事件监听器,减少内存占用。对于大量缩略图,考虑虚拟滚动技术。动态加载缩略图时,使用Intersection Observer实现懒加载。
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});
document.querySelectorAll('.thumbnail[data-src]').forEach(img => {
observer.observe(img);
});






