繁体   English   中英

使用 Vanilla JS 从其他页面平滑滚动

[英]Smooth scroll from another pages with Vanilla JS

我用香草js创建了一个平滑的滚动。 我可以在页面内滚动。 但是,当来自另一个页面时,它会转到#position 目录,然后启动 animation。 我希望他们喜欢这样:单击另一个页面中的锚链接时,页面首先显示在顶部(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>

这不能用 JavaScript 和锚链接来完成,因为当 JS 运行时,页面已经跳转到锚点。

但是,您只需几行 CSS 就可以做到这一点。

/**
 * Smooth scrolling on the whole document
 */
html {
    scroll-behavior: smooth;
}

@media screen and (prefers-reduced-motion: reduce) {
    html {
        scroll-behavior: auto;
    }
}

您可以在此处了解有关其工作原理的更多信息: https://gomakethings.com/smooth-scrolling-links-with-only-css/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM