Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. document.addEventListener("DOMContentLoaded", ready);
  2.  
  3. function ready() {
  4. const ul = document.querySelectorAll('.js-nav-menu')[0];
  5. const linkNav = document.querySelectorAll('[href^="#"]');
  6. const V = 0.5; // скорость, может иметь дробное значение через точку
  7.  
  8. ul.onclick = function(event) {
  9. const target = event.target;
  10. const hash = target.getAttribute('href'); // id элемента, к которому нужно перейти
  11. if (!hash || hash.indexOf('#') < 0) return;
  12. event.preventDefault();
  13. const w = window.pageYOffset; // прокрутка
  14. const t = document.querySelector(hash).getBoundingClientRect().top; // отступ от окна браузера до id
  15. let start = null;
  16. requestAnimationFrame(step); // подробнее про функцию анимации [developer.mozilla.org]
  17. function step(time) {
  18. if (start === null) start = time;
  19. let progress = time - start;
  20. let r = (t < 0 ? Math.max(w - progress/V, w + t) : Math.min(w + progress/V, w + t));
  21. window.scrollTo(0,r);
  22. if (r != w + t) {
  23. requestAnimationFrame(step)
  24. } else {
  25. location.hash = hash // URL с хэшем
  26. }
  27. }
  28. }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement