2016-08-04 47 views
1

鏈接的jsfiddle - https://jsfiddle.net/dn5t2mwm/3/爲什麼滾動不能正常工作?

$('a.item_link').click(function(){ 
    var hash = this.hash, top = $(hash).offset().top; 
    console.log(hash, top); 
    $('html, body').animate({ 
     scrollTop: top 
    }, 500); 
    return false; 
}); 

我要讓平滑滾動。但是當我使用錨來記錄鏈接的座標時,它會返回不同的結果。它看起來像從視口的開始處開始座標 - 而不是文檔的開始。它適用於codepen,但不適用於本地和jsfiddle。 css被禁用。也許你知道它有什麼問題嗎?

+0

'VAR哈希= this.hash'?可能你的意思是'var hash = this.href' – metal03326

+0

我不明白什麼是錯的?!哪裏有問題? – eisbehr

+0

$('html,body')。animate({scrollTop:top },5000);增加滾動時間。這將是更多smoth –

回答

0

使用這段代碼:

$('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

它不適用於底部的鏈接。 – Adoratus

+0

這是因爲頁面的左上高度小於滾動區域。這是它可以滾動的最大值。 :) –

+0

你有解決方案嗎? –