2014-10-07 84 views
0

我有一個頁面滾動腳本。單擊頁面滾動菜單時更改URL哈希值

<script> 
      $(function() { 
       $('.nav li a').bind('click',function(event){ 
        var $anchor2 = $(this).parent(); 
        var $anchor = $(this); 
        $('.nav li').removeClass('active'); 
        $anchor2.addClass('active'); 


        $('html, body').stop().animate({ 
         scrollTop: $($anchor.attr('href')).offset().top - 50 
        }, 1500,'easeInOutExpo'); 

        event.preventDefault(); 
       }); 
      }); 
     </script> 

上面的腳本完美無缺。但在地址欄中典型的URL如下

example.com/index.html 
example.com/index.html#about 
example.com/index.html#contact 

我想這個網址更改爲更加整潔使用像

example.com/about 
example.com/contact 

如果上面的網址直接訪問,它應該是在相同的滾動位置。我們如何在jQuery中做到這一點?

回答

0

使用location.hashdocument.title

$('.nav li').on('click', 'a', function(event){ 
     if ($(this).parent("li").hasClass("active")){ 
     return false; 
     }else{ 
     var go2hash = $(this).attr("data-hash"); 
     $(this).parent("li").addClass("active").siblings("li").removeClass("active"); 
     document.title = go2hash; 
     location.hash = go2hash; 
     event.preventDefault(); 
     } 
}); 

與像錨:

<nav> 
     <li><a data-hash=home>home</a></li> 
     <li><a data-hash=work>work</a></li> 
     <li><a data-hash=contact>contact</a></li> 
<nav> 
0

如果你是在Apache和關心的只是從您的網站外清潔的網址,你可以用一個ModRewrite規則.htaccess文件放在你的根目錄下。

本示例將example.com/contact的請求重定向到example.com/#contact,並在正確的部分加載頁面。

RewriteEngine on 
RewriteBase/
RewriteRule ^([a-z]+)/?$ /#$1 [R,NE,L] 

一旦進入網站,哈希將回來。我不知道你的情況是否是一個交易斷路器。