Плавная прокрутка с других страниц с помощью Vanilla JS - PullRequest
1 голос
/ 28 апреля 2020

Я создал плавный свиток с ванилью js. Я сделал это хорошо для прокрутки в пределах страницы. Но при переходе с другой страницы он идет в каталог # position, затем запускает анимацию. Мне бы хотелось, чтобы им понравилось это: при нажатии на ссылку привязки на другой странице сначала отображается страница (window.pageYOffset), а затем переходите к позициям каждой ссылки.

Я написал это событие во фрагменте начиная с if (urlHash) {}

const anchors = document.querySelectorAll('a[href^="#"]');
const header = document.querySelector('header').offsetHeight; 
const urlHash = location.hash; 


for ( let i = 0; i < anchors.length; i++ ) {
  anchors[i].addEventListener('click', (e) => {
    e.preventDefault();
    const href= anchors[i].getAttribute("href");

    if (href !== '#top') {

      const target = document.getElementById(href.replace('#', ''));

      const position = window.pageYOffset + target.getBoundingClientRect().top - header;

      window.scroll({
        top: position, 
        behavior: 'smooth' 
      });

    } else {
      window.scroll({
        top: 0, 
        behavior: 'smooth' 
      });

    }
  });
}

window.addEventListener('DOMContentLoaded', (event) => {
	if (urlHash) {
		setTimeout(function () {

      const urlTarget = document.getElementById(urlHash.replace('#', ''));

      const urlPosition = window.pageYOffset + urlTarget.getBoundingClientRect().top - header;
      window.scroll({
        top: urlPosition, 
        behavior: 'smooth' 
      });
		}, 1000); 
	}
});
* {margin: 0; padding: 0; list-style: none; box-sizing: border-box; text-decoration: none;}
header {position: fixed; width:100%; height: 100px; background: #ccc;}
div {height: 200vh;}
a {display: block;}
main{padding-top: 100px;}
<header>header</header>
<main>
<a href="#block01">Move to block01</a>
<a href="#block02">Move to block02</a>

<div id="block01">block01</div>
<div id="block02">block02</div>

<a href="#top">To top</a>
</main>
...