//Chrome和Firefox中均受支持,但不支持Edge或Safaridocument.querySelector('.hello').scrollIntoView({ behavior: 'smooth' });let mainNavLinks = document.querySelectorAll("nav ul li a");mainNavLinks.forEach(link => { link.addEventListener("click", event => { event.preventDefault(); let target = document.querySelector(event.target.hash); target.scrollIntoView({ behavior: "smooth", block: "start" }); });});//CSS可以做到这一点!有一个scroll-behaviorhtml { scroll-behavior: smooth;}复制代码
所在位置标识
let mainNavLinks = document.querySelectorAll("nav ul li a");let mainSections = document.querySelectorAll("main section");let lastId;let cur = [];window.addEventListener("scroll", event => { let fromTop = window.scrollY; mainNavLinks.forEach(link => { let section = document.querySelector(link.hash); if ( section.offsetTop <= fromTop && section.offsetTop + section.offsetHeight > fromTop ) { link.classList.add("current"); } else { link.classList.remove("current"); } });});//lodash 方法window.addEventListener("scroll", () => { _.throttle(doThatStuff, 100);});复制代码