简体   繁体   English

在URL中隐藏锚标签[参考:Rails在URL中隐藏#anchor标签]

[英]Hide anchor tag in URL [Ref: Rails hide #anchor tag in URL]

I'm adopting @Old Pro's answer: 我采用@Old Pro的答案:

history.replaceState({}, '', window.location.href.substring(0, window.location.href.indexOf('#')))

My objectives are: 我的目标是:

  1. To redirect from Page 1 to Page 2 and jump to anchor #DivTgt 从页面1重定向到页面2并跳转到锚点#DivTgt

  2. Once redirected, will remove #DivTgt from the URL. 重定向后,将从网址中删除#DivTgt。 Therefore the URL will only display page2.php and not page2.php#DivTgt 因此,URL仅显示page2.php,而不显示page2.php#DivTgt

@Old Pro's method works perfectly on Firefox but not on Chrome/Safari. @Old Pro的方法可以在Firefox上完美运行,但不能在Chrome / Safari上运行。 For Chrome/Safari, it does redirect and #DivTgt removal but doesnt jump to anchor #DivTgt. 对于Chrome / Safari,它会重定向并删除#DivTgt,但不会跳转到锚定#DivTgt。 @Old Pro's method is inserted on Page2 (target page). @Old Pro的方法已插入到Page2(目标页面)上。

I've tried both replaceState and pushState and both return a same result (ie only works on Firefox) 我试过replaceState和pushState都返回相同的结果(即仅在Firefox上有效)

Did i miss anything. 我错过了什么吗?

First of all, I would suggest to move your JavaScript code into .ready() function. 首先,我建议将您的JavaScript代码移动到.ready()函数中。 Otherwise your code may be called when DOM is not yet ready. 否则,当DOM尚未准备就绪时,您的代码可能会被调用。

I can not tell you why it's not working, but apparently some problems are existing with new html5 push and replace state functions due to no clear specs. 我不能告诉你为什么它不起作用,但是由于没有明确的规格,显然新的html5 push和replace状态函数存在一些问题。 Please read: history.replaceState() example? 请阅读: history.replaceState()示例?

So to help you, I can propose a workaround. 因此,为了帮助您,我可以提出一种解决方法。 Keep your push/replace state function, and force scrolling to your anchor with javascript. 保持推送/替换状态功能,并使用javascript强制滚动到锚点。

Can you have a look at my example please ? 你能看看我的例子吗? http://francoisjeunesse.be/example/page1.php http://francoisjeunesse.be/example/page1.php

Page1.php: page1.php中:

<a href="page2.php#DivTgt">Go to Page 2</a>

Page2.php: 使page2.php:

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js" ></script>
<script type="text/javascript"> 
$( document ).ready(function() {
    if (window.location.href.indexOf('#DivTgt') != -1){
        document.getElementById("DivTgt").scrollIntoView(true);
    }
    history.pushState({}, '', window.location.href.substring(0, window.location.href.indexOf('#')));

});
</script>
</head>
<body>
<div style="border:1px solid #000;min-height:1000px">spacer</div>
<a id="DivTgt" name="DivTgt"/>anchor is here</a>
</body>
</html>

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

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