Edit Div when scrolled over (like in google docs)

后端 未结 1 1381
故里飘歌
故里飘歌 2021-01-27 07:04

Basically I want to code something as seen in the google docs home

when you open it up it has the template section then organizing section then your documents

bu

相关标签:
1条回答
  • 2021-01-27 08:01

    You'd simply add a listener for when the user is scrolling, then if the user has scrolled a set amount of pixels do something.

    window.addEventListener('scroll', () => {
        console.log("scrolled")
    }
    

    Now when scrolling the text "scrolling" will be logged in the console. So now we need to add an if statement, checking if you've scrolled to a certain amount down the page, this is calculated in pixels.

    window.addEventListener('scroll', () => {
        if (document.body.scrollTop > 50 {
            console.log("User Scrolled past 50pixels
        }
    }
    

    Now when you've scrolled 50px down the page the console will log it. So you'd just have to change the css code of the navbar to have a fixed position at the top, as soon as you've scrolled down to it, and when you scroll above 50px remove that CSS.

    window.addEventListener('scroll', () => {
        if (document.body.scrollTop > 50 {
            // Make the div fixed here
        } else {
            // Remove the css making the div fixed
        }
    }
    

    Of course the 50 can be changed to any number you prefer. For example on Google Docs, it makes the nav fixed when you've scrolled about 205px down...

    Hope this helps!

    0 讨论(0)
提交回复
热议问题