简体   繁体   English

HTML-自动跳转到命名锚点

[英]HTML - Auto Jump to Named Anchors

I have a website that has a search box and some options. 我有一个带有搜索框和一些选项的网站。 On the mobile page, this search box and options are visible first, which is really good on the start page. 在移动页面上,首先显示此搜索框和选项,这在初始页面上确实不错。 But when user searches something, the result is shown in a page having again the search box and options on top. 但是,当用户搜索某些内容时,结果将显示在页面上,该页面的搜索框和选项再次位于顶部。

I would like to write a piece of code, that automatically jumps to content start. 我想写一段代码,它会自动跳转到内容开始。 Simply, I have created an anchor using: <a name="contentstart"> just before the content. 简而言之,我使用以下内容创建了一个锚点: <a name="contentstart"> When the user opens this page, it should automatically jump to contentstart without having to press any link/button. 当用户打开此页面时,它应自动跳转到contentstart而无需按任何链接/按钮。 How can I achieve that. 我该如何实现。

simply give an id to your a tag, 只需为您a标签提供ID,

and use following javascript function : 并使用以下javascript函数:

function jump(id){
    var top = document.getElementById(id).offsetTop; //Getting Y of target element
    window.scrollTo(0, top);                        //Go there.
}​

and in onload of body tag, call the function by passing the id of the anchor tag 在body标签的onload中,通过传递锚标签的ID来调用函数

You can simple use id and hash in url. 您可以在url中简单使用id和hash。

// some html
<div id="contentstart"></div>
// content

After that if you sufix your url with #contentstart you jump right to constentstart div. 之后,如果您使用#contentstart来添加网址,则可以直接跳转到constentstart div。

http://webpage.com/something#contentstart

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

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