使用Javascript从其他页面平滑滚动

问题描述 投票:0回答:1

我使用javascript创建了平滑的滚动。我确定可以在页面内滚动。但是,当来自另一个页面时,它将转到#position目录,然后开始动画。它写在代码段if (urlHash) {}区域。

我想让页面首先显示在主体顶部,然后在1秒后从另一个页面进入,例如单击index.html#block02时移至链接位置。

我不知道。请帮忙。非常感谢。

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) {
    window.scrollTo({top:0});
    setTimeout(function () {

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

      const urlPosition = window.pageYOffset + urlTarget.getBoundingClientRect().top - header;
      window.scroll({
        top: urlPosition,
        behavior: 'smooth'
      });
    }, 1000);
  }
});
header {position: fixed; width:100%; height: 100px; text-align:center; border-bottom:1px solid #ccc;}
div {height: 200vh;}
a {display: inline-block;}
main{padding-top: 100px;}
<header>header</header>
<main>
<a href="#block01">block01へ移動</a>
<a href="#block02">block02へ移動</a>

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

<a href="#top">topへ戻る</a>
</main>
javascript scroll hyperlink anchor smooth-scrolling
1个回答
0
投票

只需重置脚本顶部的滚动位置:

setTimeout(() => { window.scrollTo(0, 0) }, 0) // Here

const anchors = document.querySelectorAll('a[href^="#"]');
const header = document.querySelector('header').offsetHeight;
const urlHash = location.hash;
// ...
© www.soinside.com 2019 - 2024. All rights reserved.