zishu's blog

zishu's blog

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

How to solve the issue of the window.scroll method can only exist once?

slug: 55
title: How to solve the problem of window.scroll method only being able to exist once?
date: 2021-03-17 21:55:00
updated: 2021-12-01 09:01:36
categories:

  • Technology
    tags:
  • IE

Page scrolling is a commonly used functionality, and the following two code snippets represent two events that are triggered when the page is scrolled 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 make the code 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 latter ones will not work.

So how to solve this problem?

window.scroll can only exist once, the first one will work, and the later ones will not work. 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('Second 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.