Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- document.addEventListener("DOMContentLoaded", ready);
- function ready() {
- const ul = document.querySelectorAll('.js-nav-menu')[0];
- const linkNav = document.querySelectorAll('[href^="#"]');
- const V = 0.5; // скорость, может иметь дробное значение через точку
- ul.onclick = function(event) {
- const target = event.target;
- const hash = target.getAttribute('href'); // id элемента, к которому нужно перейти
- if (!hash || hash.indexOf('#') < 0) return;
- event.preventDefault();
- const w = window.pageYOffset; // прокрутка
- const t = document.querySelector(hash).getBoundingClientRect().top; // отступ от окна браузера до id
- let start = null;
- requestAnimationFrame(step); // подробнее про функцию анимации [developer.mozilla.org]
- function step(time) {
- if (start === null) start = time;
- let progress = time - start;
- let r = (t < 0 ? Math.max(w - progress/V, w + t) : Math.min(w + progress/V, w + t));
- window.scrollTo(0,r);
- if (r != w + t) {
- requestAnimationFrame(step)
- } else {
- location.hash = hash // URL с хэшем
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement