2015-11-03 74 views
0

我想在我的網站上使用Smooth Scroll,但我需要URL上的錨點ID來提供瀏覽器後退按鈕的功能。問題是:我需要在400 ms之前顯示#anchor,但我不知道如何在腳本中調用該變量。在URL上使用錨點進行平滑滾動

$(document).ready(function(){ 
    $('a[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) { 
     var targetOffset = $target.offset().left; 
     $('html,body') 
     .animate({scrollLeft: targetOffset}, 400); 
var timer = setTimeout(function() { 
     window.location.href = '#[anchor]'; 
    }, 400); 
     return false; 
     } 
    } 
    }); 
}); 

window.location.href = '#[anchor]';更改URL,但不與錨點名稱。我該如何改變它?

+0

什麼是主播的名字嗎? –

+0

不幸的是,不僅僅是一個錨,問題是我需要每次在這之間滾動時頁錨。 –

+0

我看了我的代碼,在那裏我做了相同的事情,並調整了代碼來實現它,它是否適合您? –

回答

0

錨存儲在hash變量,看到的例子,並檢查意見:

if (target.length) { 

    var _this = this; // first save the reference to 'this' 

    var targetOffset = $target.offset().left; 
    $('html,body').animate({scrollLeft: targetOffset}, 400); 
    var timer = setTimeout(function() { 
     window.location.href = _this.hash; // '_this.hash' contains the anchor 
    }, 400); 
    return false; 

您也可以使用window.location.hash這樣的:

window.location.hash = _this.hash;