2014-03-26 40 views
0

我使用以下腳本來平滑滾動效果減去一頁上的像素量。問題是,我點擊一個錨鏈接,滾動效果就像它應該那樣工作,但是然後我滾動回鏈接所在頁面的頂部並點擊另一個頁面。它不起作用。我剛從網頁上覆制腳本,我的JavaScript非常糟糕。Javascript平滑滾動 - 不能使用第二次點擊

Thx尋求幫助。

function filterPath(string) { 
    return string 
     .replace(/^\//,'') 
     .replace(/(index|default).[a-zA-Z]{3,4}$/,'') 
     .replace(/\/$/,''); 
    } 
    var locationPath = filterPath(location.pathname); 
    var scrollElem = scrollableElement('html', 'body'); 

    $('a[href*=#]').each(function() { 
     var thisPath = filterPath(this.pathname) || locationPath; 
     if ( locationPath == thisPath 
     && (location.hostname == this.hostname || !this.hostname) 
     && this.hash.replace(/#/,'')) { 
      var $target = $(this.hash), target = this.hash; 
      if (target) { 
       var targetOffset = $target.offset().top - 70; 
       $(this).click(function(event) { 
       if(event != 'undefined') { 
        event.preventDefault();} 
        $(scrollElem).animate({scrollTop: targetOffset}, 400, function(e) { 
        e.preventDefault(); 
        location.hash = target; 
       }); 
      }); 
     } 
    } 
}); 

function scrollableElement(els) { 
    for (var i = 0, argLength = arguments.length; i <argLength; i++) { 
     var el = arguments[i], 
      $scrollElement = $(el); 
     if ($scrollElement.scrollTop()> 0) { 
      return el; 
     } else { 
      $scrollElement.scrollTop(1); 
      var isScrollable = $scrollElement.scrollTop()> 0; 
      $scrollElement.scrollTop(0); 
      if (isScrollable) { 
       return el; 
      } 
     } 
    } 
} 
+0

可你也許粘貼一些你的HTML嗎? – webeno

+0

不確定你從哪裏得到這個信息,但是因爲你沒有共享任何html,所以我建議你做一件事,那就是嘗試使用現有的腳本,比如[this one](http:///cferdinandi.github.io/smooth-scroll/) - 看起來很簡單... – webeno

回答

0

代碼出現錯誤。

凡說:

$(scrollElem).animate({scrollTop: targetOffset}, 400, function(e) { 
    e.preventDefault(); 
    location.hash = target; 
}); 

您正在呼籲沒有preventDefault()。保持原樣並且它可以工作:

$(scrollElem).animate({scrollTop: targetOffset}, 400, function() { 
    location.hash = target; 
}); 
0

錯誤發生在代碼的開始處。而不是使用each循環,您應該將一個click事件添加到錨元素。通過使用each循環,您只添加一次點擊事件,因此在第二次點擊時,事件爲undefined,並且代碼會發生錯誤。

這裏是你的代碼改寫爲click事件:

$('a[href*=#]').click(function(e){ 
    var thisPath = filterPath(this.pathname) || locationPath; 
    if (locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/,'')) { 
    var $target = $(this.hash), target = this.hash; 
    if (target) { 
     var targetOffset = $target.offset().top - 70; 
     $(scrollElem).animate({scrollTop: targetOffset}, 400, function() { 
     if(e != 'undefined') { 
      e.preventDefault(); 
     } 
     location.hash = target; 
     }); 
    } 
    } 
}); 

希望這有助於;-)