編輯問題,以包括預(yù)期行為、特定問題或錯(cuò)誤以及重現(xiàn)問題所需的最短代碼。這將有助于其他人回答問題。
這里有一個(gè)可能解決你的問題的方法,把它添加到你的html代碼的末尾,在一個(gè)腳本標(biāo)簽中...
// Get a reference to your menu links
const menuLinks = document.querySelectorAll('a[href^="#"]');
// Attach a click event listener to each menu link
menuLinks.forEach(link => {
link.addEventListener('click', event => {
event.preventDefault(); // Prevent the default scroll behavior
// Get the target element's ID from the href attribute
const targetId = link.getAttribute('href').slice(1);
const targetElement = document.getElementById(targetId);
// Scroll smoothly to the target element
targetElement.scrollIntoView({ behavior: 'smooth' });
// Update the URL manually with the anchor link
history.pushState(null, null, `#${targetId}`);
});
});