2009-12-21 78 views
43

我有以下代碼:變化哈希jQuery中

$('ul.questions li a').click(function(event) { 
    $('.tab').hide(); 
    $($(this).attr('href')).fadeIn('slow'); 
    event.preventDefault(); 
    window.location.hash = $(this).attr('href'); 
}); 

這只是變淡一個div基於當你點擊,但我想要的網頁URL哈希標籤更改當您單擊讓人們可以複製併爲其添加書籤。目前,當散列標籤發生變化時,這會有效地重新加載頁面。

是否可以更改哈希標記並且不重新加載頁面以防止跳躍效應?

+1

我跑這個當前頁面上的下面,才正是你想要的(沒有重新加載頁面):$( 「A」)點擊(函數(事件){event.preventDefault();窗口。 location.hash = $(this).attr('href');})。也許在你的代碼運行的時候,頁面還沒有加載?檢查中有多少項目在'$(「ul.questions李一」)' – 2009-12-21 09:49:48

回答

70

這對我的作品在這裏http://jsbin.com/edicu

$('ul.questions li a').click(function(event) { 
    event.preventDefault(); 
    $('.tab').hide(); 
    window.location.hash = this.hash; 
    $($(this).attr('href')).fadeIn('slow'); 
}); 

檢查演示幾乎相同的代碼

+0

你好,是的,它不會起作用,但是當頁面滾動時的散列鏈接改變它跳轉到div。 – daveredfern 2009-12-21 11:50:01

+0

檢查修改過的代碼。如果你不想發生這種情況,你只需要切換最後兩行。原來的順序是你的,我一直是這樣,因爲我認爲這就是你想要的 – jitter 2009-12-21 12:05:33

+0

謝謝:)做的工作很棒。 – daveredfern 2009-12-21 16:01:13

4

您可以嘗試捕獲onload事件。並停止傳播依賴於一些標誌。

var changeHash = false; 

$('ul.questions li a').click(function(event) { 
    var $this = $(this) 
    $('.tab').hide(); //you can improve the speed of this selector. 
    $($this.attr('href')).fadeIn('slow'); 
    StopEvent(event); //notice I've changed this 
    changeHash = true; 
    window.location.hash = $this.attr('href'); 
}); 

$(window).onload(function(event){ 
    if (changeHash){ 
     changeHash = false; 
     StopEvent(event); 
    } 
} 

function StopEvent(event){ 
    event.preventDefault(); 
    event.stopPropagation(); 
    if ($.browser.msie) { 
     event.originalEvent.keyCode = 0; 
     event.originalEvent.cancelBubble = true; 
     event.originalEvent.returnValue = false; 
    } 
} 

沒有測試過,所以不能說是否會工作

+1

一個,你需要將本地變量「事件」傳遞到「StopEvent」 – 2009-12-21 09:43:50

+0

哎呀。謝謝相應編輯。 – 2009-12-21 10:30:42

+0

感謝您的支持將會帶給您一個旋風。 – daveredfern 2009-12-21 11:50:41

0

接受的答案不適合我,因爲我的網頁在點擊時略微跳躍,搞亂了我的滾動動畫。

我決定使用window.history.replaceState更新整個URL,而不是使用window.location.hash方法。從而繞過瀏覽器觸發的hashChange事件。

// Only fire when URL has anchor 
$('a[href*="#"]:not([href="#"])').on('click', function(event) { 

    // Prevent default anchor handling (which causes the page-jumping) 
    event.preventDefault(); 

    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) {  
      // Smooth scrolling to anchor 
      $('html, body').animate({ 
       scrollTop: target.offset().top 
      }, 1000); 

      // Update URL 
      window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash); 
     } 
    } 
});