Created
July 15, 2020 06:37
-
-
Save renoinn/2d4671163d3b5c220ab33bce21e005ff to your computer and use it in GitHub Desktop.
素のJSでスムーススクロールする
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const links = document.querySelectorAll('a[href^="#"]') | |
| for ( let i = 0; i < links.length; i++ ) { | |
| links[i].addEventListener('click', (e) => { | |
| e.preventDefault(); | |
| const target = document.querySelector(links[i].href.substr(links[i].href.indexOf('#'))) | |
| const elemY = target.getBoundingClientRect().top | |
| const scrollY = window.pageYOffset | |
| const top = Math.abs(elemY + scrollY) | |
| console.log(`${elemY} - ${scrollY} = ${top}`) | |
| window.scroll({ | |
| top: top, | |
| behavior: 'smooth' | |
| }) | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment