2013-04-22 39 views
2

我使用JavaScript导航到主页上的锚。从主页中,当我点击一个锚链接,网址是一样的:本地主机/(使用JavaScript ScrollTo),但是当我尝试从一个单独的页面链接到的锚标记它显示在URL中的锚标记。本地主机/#锚。Rails的隐藏#anchor标签在URL

我怎么能掩盖的URL不显示锚标记?

<li><%= link_to "Anchor", root_path(:anchor => 'anchor') %></li> 

的jQuery:

$('a[href*=#]:not([href=#])').click(function() { 
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
     || location.hostname == this.hostname) { 

     var target = $(this.hash); 
     target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
      if (target.length) { 
      $('html,body').animate({ 
       scrollTop: target.offset().top 
      }, 1000); 
      return false; 
     } 
    } 
+0

哪个库提供了这个scrollTo方法,prototype? jQuery的?答案可能完全不同。 – 2013-04-26 05:09:36

+0

是的,我使用jQuery。代码粘贴在下面。 – agassi0430 2013-04-27 06:06:40

回答

4

当你点击锚你不实际提交到Rails的请求主页上,你只是执行一个单击处理。但是,当你从另一个页面来,那么你提交请求到Rails和#fragment是任何人都知道在网页上滚动到的唯一途径。

你可以做的最好的是探测JS的#fragment时加载页面,滚动到合适的位置,并与

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

假设你有一个支持replaceState浏览器中删除片段。如果你想是很好的旧的浏览器可以使用History.js

0

你可以做window.location.hash.replace('#', '');