zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

How to resolve the issue of having only one occurrence of the window.scroll method?

Page listening is a function we often use. The following two code snippets represent two events that are triggered when the page scrolls to 500px and 1000px respectively. Arrow functions are used in the code.

window.addEventListener('scroll', () => {
   var scrollTop = document.documentElement.scrollTop 
   if (scrollTop > 500) {
       console.log('Scrolled 500px')
   }
})

window.addEventListener('scroll', () => {
   var scrollTop = document.documentElement.scrollTop 
   if (scrollTop > 1000) {
        console.log('Scrolled 1000px')
   }
})

However, later it is required to be compatible with IE10, so this writing style cannot be used. Then I thought of using the native function syntax.

window.onscroll = function() {
    // ...
}

In the process of using it, I found that if there is only one window.scroll, there is no problem, but if there are multiple window.scroll, the ones after the first one will not work.

So how to solve this problem?

window.scroll can only exist once. The first one will work, and the ones after it will not. This problem can be solved by handling it with JavaScript.

function addEvent(type, toDo) {
    if (window.attachEvent) {
        window.attachEvent('on' + type, function() {
            toDo.call(window)
        })
    } else {
        window.addEventListener(type, toDo, false)
    }
}

addEvent('scroll', function(){
    console.log('First call to window.scroll')
}

addEvent('scroll', function(){
    console.log('First call to window.scroll')
}

Run it, and multiple scroll events can run simultaneously.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.