我有两个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上起作用。在谷歌上搜索后,我找到了一些线索:
在我的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中看到了以下内容:
原始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
问题,那将会更好,因为back bottom问题是该代码的结果。
发布于 2019-07-13 07:25:23
为了回答您关于为什么会发生这种情况的问题,我将解释这段代码在做什么。
一旦你登陆到第二个页面(历史上的第一个网址),这段代码等待文档被加载($(document).ready
),然后执行传递给它的回调,该回调检查浏览器是否是Chrome,如果是,它就在消息总线(setTimeout
)上添加一个回调,它从网址中抓取散列,它从网址中移除散列(历史上的第二个网址),然后将其添加回网址(历史上的第三个网址,并最终“滚动”到该ID)。
我已经用注释注释了你的代码。
$(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);
}
});
https://stackoverflow.com/questions/57015513
复制相似问题