我有3个文件:
- mainPage.html
- starter.html
- Landing.js
当我点击starter.html中的div时,我想移动到mainPage.html,然后移动到该页面的菜单部分
starter.html代码:
<li> <div onclick="onBackToMenu()">Back to menu</div></li>
landing.js代码:
function onBackToMenu() {
window.location.href = "../mainPage.html";
document.getElementById("Menu").scrollIntoView();
}
mainPage.html:(部分代码(
<!-- Menu section -->
<span class="anchor-offset" id="Menu"></span>
<div class ="section" >
<div class ="sectionHeadings">
<h1>Menu/Products</h1>
<div class="menu">
<div class="starter" onclick="location.href='pages/starter.html';">
<h3 class="menu-heading starter-heading">Starters</h3>
</div>
当我点击div时,它确实会把我带到mainPage.html,但它不想带我到id为Menu的Menu部分。
请帮助
由于您已经有了该部分的id===><span class="anchor-offset" id="Menu"></span>
在href末尾传递id,如下所示:window.location.href = "../mainPage.html#Menu";
当加载新页面时,这将引导您进入该部分。
function onBackToMenu() {
window.location.href = "../mainPage.html#Menu";
document.getElementById("Menu").scrollIntoView();
}
不需要javascript。使用锚元素(<a>
(和href
元素来创建一个指向新页面的超链接,该超链接带有要滚动到的部分的片段标识符,这是更好的做法,对可访问性也更好。
在您的情况下,只需将starter.html中的列表项更改为:
<li><a href="../mainPage.html#Menu">Back to menu</a></li>
这会将用户导航到新页面的菜单部分。