简体   繁体   English

如何使用 Javascript 方法移动到另一个页面,然后移动到页面的某个部分

[英]How to move to another page and then to a certain section of the page using a Javascript method

I have 3 files:我有 3 个文件:

  • mainPage.html主页.html
  • starter.html启动器.html
  • Landing.js登陆.js

When I click on the div in starter.html I want to move to mainPage.html and then to the Menu section of this page当我单击starter.html中的 div 时,我想移至mainPage.html ,然后移至此页面的菜单部分

starter.html code: starter.html 代码:

<li> <div onclick="onBackToMenu()">Back to menu</div></li>

landing.js code:登陆.js代码:

function onBackToMenu() {
   window.location.href = "../mainPage.html";

   document.getElementById("Menu").scrollIntoView();

}

mainPage.html: (partial code) 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>

When I click on the div then it does take me to mainPage.html, but it doesnt want to take me to the Menu section with id of Menu.当我单击 div 时,它确实将我带到 mainPage.html,但它不想将我带到具有菜单 ID 的菜单部分。

Please help请帮忙

Since you have an id on that section already ==> <span class="anchor-offset" id="Menu"></span> pass the id at the end of your href like this: window.location.href = "../mainPage.html#Menu";由于您在该部分已经有一个 id ==> <span class="anchor-offset" id="Menu"></span>在您的 href 末尾传递 id,如下所示: window.location.href = "../mainPage.html#Menu"; this will a direct you to that section when the new page loads.当新页面加载时,这将引导您到该部分。

function onBackToMenu() {
   window.location.href = "../mainPage.html#Menu";

   document.getElementById("Menu").scrollIntoView();

}

No javascript is necessary.不需要 javascript。 It's better practice and better for accessibility to use an anchor element ( <a> ) with an href element to create a hyperlink to the new page with a fragment identifier for the section you want to scroll to.使用带有href元素的锚元素 ( <a> )来创建指向新页面的超链接是更好的做法和更好的可访问性,该新页面带有要滚动到的部分的片段标识符

In your case, just change the list item in starter.html to:在您的情况下,只需将starter.html中的列表项更改为:

<li><a href="../mainPage.html#Menu">Back to menu</a></li>

This will navigate a user to the menu section of the new page.这会将用户导航到新页面的菜单部分。

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

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