Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
876 views
in Technique[技术] by (71.8m points)

foreach - Same scroll event to fire on multiple instances of element - vanilla javascript

I am trying to get 3 separate animations to move while I scroll down the page. The behaviour is the same for all of them, so I have tried using forEach.

const svgContainer = document.querySelectorAll('.svg-container')
const textPath = document.querySelectorAll('.text-path')
const path = document.querySelectorAll('#wave');
const pathLength = path.getTotalLength();

const moveText = () => {
    requestAnimationFrame(function() {
        let scrollPercent;
        svgContainer.forEach(x => {
            scrollPercent = x.getBoundingClientRect().y / window.innerHeight;
        })
        textPath.forEach(x => {
            x.setAttribute('startOffset', scrollPercent * pathLength);
        })
    })
}
window.addEventListener('scroll', moveText);

However this doesn't work - see full code here: https://jsfiddle.net/chunzg/knr2y4ft/13/

(The 'Heading 1', 'Heading 2', and 'Heading 3' should move across horizontally from right to left of the screen as we scroll down, and move left to right as we scroll back up)

I then tried a different way, adding different class names to each instance, and grabbing all of them with querySelectorAll:

const svgContainer = document.querySelectorAll('.svg-container-1, .svg-container-2, .svg-container-3')
const textPath = document.querySelectorAll('.text-path-1, .text-path-2, .text-path-3')
const path = document.querySelectorAll('#wave-1, #wave-2, #wave-3');
const pathLength = path.getTotalLength();

const moveText = () => {
    requestAnimationFrame(function() { 
        var rect = svgContainer.getBoundingClientRect();
        var scrollPercent = rect.y / window.innerHeight;
        textPath.setAttribute('startOffset', scrollPercent * pathLength);
    })
}
window.addEventListener('scroll', moveText);

but doesn't work either: https://jsfiddle.net/chunzg/py0gox1n/16/

Where am I going wrong?

The only other way I can think of is to repeat the script for each heading separately but this wouldn't be dry code?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...