我想为滚动上的许多元素实现不同的动画,所以不是使用window.scroll,而是使用交集观察器api,但是我想知道我的方法是否有效并且不会导致性能下降,基本上是什么我所做的是制作一个函数来保存网站的整个动画,并检查目标是否具有特定的类,然后执行以下操作:
const one = document.querySelector('.one')
const two = document.querySelector('.two')
const three = document.querySelector('.three')
function animation (entires) {
entires.forEach(entry => {
if(entry.isIntersecting) {
if(entry.target.classList.contains('text')) {
entry.target.style.transform = 'translateY(0)'
}
if(entry.target.classList.contains('one')) {
entry.target.style.transform = 'translateX(100px)'
}
if(entry.target.classList.contains('two')) {
entry.target.style.transform = 'translateY(0)'
}
if(entry.target.classList.contains('three')) {
entry.target.style.transform = 'skew(10deg)'
}
}
})
}
const observer = new IntersectionObserver(animation)
我经验不足,但是我觉得这是意大利面条代码,效率不高,我如何观察多个元素?我是否必须对要观察的每个元素重复observer.observe?
答案 0 :(得分:2)
Intersection Observer API
有助于确定特定元素是否在视口中可见,并且动画是此API的理想用例,因此性能没有下降,相反,它的性能比{{1 }}。但是在像这样的小例子中,它并不是很引人注目。
您也可以将其用于:
https://jsfiddle.net/v6hyqtoa/
window.scroll
const one = document.querySelector('.one')
const two = document.querySelector('.two')
const three = document.querySelector('.three')
const divs = [one, two, three];
function animation(entires) {
entires.forEach(entry => {
if (entry.isIntersecting) {
if (entry.target.classList.contains('one')) {
entry.target.style.transform = 'translateX(100px)'
}
if (entry.target.classList.contains('two')) {
entry.target.style.transform = 'translateY(0)'
}
if (entry.target.classList.contains('three')) {
entry.target.style.transform = 'skew(10deg)'
}
}
})
}
const observer = new IntersectionObserver(animation)
divs.forEach((div) => observer.observe(div));