Javascript 使用javascript进行锚点跳跃

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13735912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:46:39  来源:igfitidea点击:

anchor jumping by using javascript

javascripthtmlfunctionanchorhref

提问by bonny

I have a question that will be found very often. The problem is that nowhere can be found an explicit solution.

我有一个经常会被发现的问题。问题是没有任何地方可以找到明确的解决方案。

I have two problems regarding anchors.

我有两个关于锚点的问题。

The main goal should be to get a nice clean url without any hashes in it while using anchors to jump on a page.

主要目标应该是在使用锚点跳转到页面时获得一个干净的 url,其中没有任何哈希值。

So the structure of the anchors is:

所以anchors的结构是:

<ul>
    <li><a href="#one">One</a></li>
    <li><a href="#two">Two</a></li>
    <li><a href="#three">Three</a></li>
</ul>

<div class="wrap">
    <a name="one">text 1</a>
    <a name="two">text 2</a>
    <a name="three" class="box">text 3</a>
</div>

Okay, if you will click one of the links the url will automatically change to

好的,如果您单击其中一个链接,网址将自动更改为

www.domain.com/page#1

www.domain.com/page#1

At the end this should be just:

最后这应该只是:

www.domain.com/page

www.domain.com/page

So far, so good. Now the second thing is, when you search the internet for that problem you will find javascriptas a solution.

到现在为止还挺好。现在第二件事是,当您在互联网上搜索该问题时,您会找到javascript解决方案。

I have found this function:

我找到了这个功能:

function jumpto(anchor){
    window.location.href = "#"+anchor;
}

and calling that function with:

并使用以下命令调用该函数:

<a onclick="jumpto('one');">One</a>

what will be the same like before. It will add the hash to the url. I also added

什么会和以前一样。它将哈希添加到 url。我还加了

<a onclick="jumpto('one'); return false;">

without success. So if there is someone who could tell me how to solve this I really would appreciate.

没有成功。因此,如果有人可以告诉我如何解决这个问题,我将不胜感激。

Thanks a lot.

非常感谢。

回答by u283863

You can get the coordinate of the target element and set the scroll position to it. But this is so complicated.

您可以获取目标元素的坐标并为其设置滚动位置。但这太复杂了。

Here is a lazier way to do that:

这是一种更懒惰的方法:

function jump(h){
    var url = location.href;               //Save down the URL without hash.
    location.href = "#"+h;                 //Go to the target element.
    history.replaceState(null,null,url);   //Don't like hashes. Changing it back.
}

This uses replaceStateto manipulate the url. If you also want support for IE, then you will have to do it the complicated way:

这用于replaceState操作 url。如果您还想支持 IE,那么您将不得不以复杂的方式进行

function jump(h){
    var top = document.getElementById(h).offsetTop; //Getting Y of target element
    window.scrollTo(0, top);                        //Go there directly or some transition
}?

Demo: http://jsfiddle.net/DerekL/rEpPA/
Another one w/ transition: http://jsfiddle.net/DerekL/x3edvp4t/

演示:http: //jsfiddle.net/DerekL/rEpPA/
另一个带过渡的:http: //jsfiddle.net/DerekL/x3edvp4t/

You can also use .scrollIntoView:

您还可以使用.scrollIntoView

document.getElementById(h).scrollIntoView();   //Even IE6 supports this

(Well I lied. It's not complicated at all.)

(好吧,我撒谎了。它一点也不复杂。)

回答by Adam111p

I think it is much more simple solution:

我认为这是更简单的解决方案:

window.location = (""+window.location).replace(/#[A-Za-z0-9_]*$/,'')+"#myAnchor"

This method does not reloadthe website, and sets the focuson the anchors which are needed for screen reader.

此方法不会重新加载网站,并将焦点设置在屏幕阅读器所需的锚点上。

回答by cmc

Not enough rep for a comment.

没有足够的代表发表评论。

The getElementById() based method in the selected answer won't work if the anchor has namebut not idset (which is not recommended, but does happen in the wild).

如果锚点已设置name但未id设置(不推荐,但确实会在野外发生),则所选答案中基于 getElementById() 的方法将不起作用。

Something to bare in mind if you don't have control of the document markup (e.g. webextension).

如果您无法控制文档标记(例如 webextension),请记住一些事情。

The locationbased method in the selected answer can also be simplified with location.replace:

location所选答案中的基于方法也可以简化为location.replace

function jump(hash) { location.replace("#" + hash) }

回答by S.Doe_Dude

I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.

我有一个提示按钮,点击它会打开显示对话框,然后我可以写我想要搜索的内容,然后它会转到页面上的那个位置。它使用 javascript 来回答标题。

On the .html file I have:

在 .html 文件中,我有:

<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>

On the .js file I have

在 .js 文件上我有

function myFunction() {
    var input = prompt("list or new or quit");

    while(input !== "quit") {
        if(input ==="test100") {
            window.location.hash = 'test100';
            return;
// else if(input.indexOf("test100") >= 0) {
//   window.location.hash = 'test100';
//   return;
// }
        }
    }
}

When I write test100into the prompt, then it will go to where I have placed span id="test100" in the html file.

当我将test100写入提示时,它将转到我在 html 文件中放置 span id="test100" 的位置。

I use Google Chrome.

我使用谷歌浏览器。

Note: This idea comes from linking on the same page using

注意:这个想法来自使用在同一页面上的链接

<a href="#test100">Test link</a>

which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.

点击后将发送到锚点。为了使其多次工作,根据经验需要重新加载页面。

Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ?

归功于stackoverflow(也可能是stackexchange)的人们不记得我是如何收集所有零碎碎片的。?

回答by Jonathan Vukovich-Tribouharet

Because when you do

因为当你做

window.location.href = "#"+anchor;

You load a new page, you can do:

您加载一个新页面,您可以执行以下操作:

<a href="#" onclick="jumpTo('one');">One</a>
<a href="#" id="one"></a>

<script>

    function getPosition(element){
        var e = document.getElementById(element);
        var left = 0;
        var top = 0;

        do{
            left += e.offsetLeft;
            top += e.offsetTop;
        }while(e = e.offsetParent);

        return [left, top];
    }

    function jumpTo(id){    
        window.scrollTo(getPosition(id));
    }

</script>