如何为IntersectionObserver API添加多类并实现不同动画?
解决IntersectionObserver给多元素添加不同动画的问题
首先,你之前用querySelector('.frontside, .img-form')无效的核心原因是:querySelector只会返回匹配选择器的第一个元素,要获取多个匹配元素,必须用querySelectorAll,再遍历每个元素做处理。
要给不同类的元素设置不同动画,你可以通过判断元素类名,对应添加不同的动画类,以下是两种适配不同场景的实现方案:
方案1:同一容器下的多子元素(你的原场景)
如果.frontside和.img-form都在.vaimalandra容器内,修改代码如下:
const observer = new IntersectionObserver(entries => { entries.forEach(entry => { // 获取容器内所有目标元素 const targetElements = entry.target.querySelectorAll('.frontside, .img-form'); targetElements.forEach(el => { if (entry.isIntersecting) { // 根据元素类名匹配对应动画 el.classList.contains('frontside') ? el.classList.add('animacion') : el.classList.add('animacion-img'); } else { // 离开视口时移除对应动画 el.classList.contains('frontside') ? el.classList.remove('animacion') : el.classList.remove('animacion-img'); } }); }); }); // 观察目标容器 observer.observe(document.querySelector('.vaimalandra'));
方案2:观察多个独立元素
如果.frontside和.img-form是互不嵌套的独立元素,可以直接观察每个元素:
const observer = new IntersectionObserver(entries => { entries.forEach(entry => { const el = entry.target; if (entry.isIntersecting) { el.classList.add(el.classList.contains('frontside') ? 'animacion' : 'animacion-img'); } else { el.classList.remove(el.classList.contains('frontside') ? 'animacion' : 'animacion-img'); } }); }); // 批量观察所有目标元素 document.querySelectorAll('.frontside, .img-form').forEach(el => { observer.observe(el); });
扩展说明
如果后续需要新增更多动画类,只需要在判断分支里添加新的类名匹配即可,比如:
// 新增一个.backside元素对应animacion-back动画 if (el.classList.contains('backside')) { el.classList.add('animacion-back'); } else { el.classList.remove('animacion-back'); }
内容的提问来源于stack exchange,提问作者Maximiliano Guyot
相关产品推荐
相关产品推荐

