在html中添加锚标记和潜在的javascript干扰问题

时间:2019-07-13 01:34:29

标签: javascript html google-chrome anchor

我有两个html页面,在第一页面中有一个指向第二页面的anchor tag的链接。

Here是第一页。页面底部有一些链接。例如,如果用户单击Analog Electronics链接,则他/他将转到包含anchor tag的第二页。

这是首页上的链接:

<a href="/electronics.html#electronics-books-suggested-by-hooman-darabi">Electronics</a>

这是第二页上的anchor tag

<h3 id="electronics-books-suggested-by-hooman-darabi">Electronics books suggested by Hooman Darabi</h3>

起初,锚定不适用于Chrome,但适用于Firefox。经过一些Google搜索后,我想出了一些线索:

在我的html文件的底部,我包括了三个JavaScript文件:

如果我注释掉这3个中的任何一个,则anchoring在Chrome和FireFox上都可以正常工作。但是,当然,我需要将这3个JS文件包含在我的页面中。

经过更多研究,我发现了这个建议:

要使anchoring正常工作并单击链接,请在显示的第二页顶部位于anchor tag的位置,我必须将此代码添加到html页面:

$(document).ready(function () {
            var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
            if (window.location.hash && isChrome) {
                setTimeout(function () {
                    var hash = window.location.hash;
                    window.location.hash = "";
                    window.location.hash = hash;
                }, 200);
            }
        });

我不知道这段代码的作用,但是它可以帮助锚定在显示的链接页面顶部显示。

尽管此代码解决了我的问题,但是现在发生了一些坏事!。如果在第二页(http://www.doradolist.com/analog.html#analog-electronics-books-suggested-by-hooman-darabi)上,我单击了Chrome的底部,则不会返回上一页。我需要按后下3次才能返回上一页。如果我查看每次按下后底部后URL发生了什么,我会在页面的URL中看到这一点:

原始网址:

http://www.doradolist.com/analog.html#analog-electronics-books-suggested-by-hooman-darabi

后退一次后单击:

http://www.doradolist.com/analog.html#

在两次单击底部后:

http://www.doradolist.com/analog.html#analog-electronics-books-suggested-by-hooman-darabi

最后点击3次后底角,我便转到原始页面。

我们将非常感谢您提供任何有关为何发生此后发问题以及如何解决此问题的帮助。或者,如果不添加我上面显示的代码,而是采用另一种方法解决Chrome中的anchoring问题,那就更好了,因为后底部的问题是该代码的结果。

1 个答案:

答案 0 :(得分:1)

要回答您为什么为什么的问题,我将解释代码片段在做什么

一旦您进入第二页(历史记录中的第一个URL),此代码段将等待文档加载($(document).ready),然后执行传递给它的回调,该回调检查浏览器是否为Chrome ,如果是,则在消息总线(setTimeout)上添加回调,该回调从URL中获取哈希,然后从URL(历史记录中的第二个URL)中删除哈希,然后将其添加回URL(历史记录中的第三个URL,最后一个“滚动”到该ID的URL)。

我已经用注释注释了您的代码。

$(document).ready(function () { // wait for document to load
            var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor); // check if browser is Chrome
            if (window.location.hash && isChrome) { // if the URL has a hash in it, and the browser is Chrome
                setTimeout(function () { // add this callback to the message bus
                    var hash = window.location.hash; // read the hash from the URL in the address bar
                    window.location.hash = ""; // set the hash in the URL in the address bar to be empty
                    window.location.hash = hash; // add the hash back to the URL in the address bar
                }, 200);
            }
        });