2015-04-22 44 views
2

我使用平滑滾動鏈接的代碼:平滑鏈接渾身不滾動,但一定DIV

function filterPath(string) { 
    return string 
     .replace(/^\//,'') 
     .replace(/(index|default).[a-zA-Z]{3,4}$/,'') 
     .replace(/\/$/,''); 
    } 

$('a[href*=#]').each(function() { 
if (filterPath(location.pathname) == filterPath(this.pathname) 
&& location.hostname == this.hostname 
&& this.hash.replace(/#/,'')) { 
    var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']'); 
    var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false; 
    if ($target) { 
     $(this).click(function() { 
      var targetOffset = $target.offset().top; 
      $('html, body, .container-1-2').animate({ 
       scrollTop: $target.offset().top - 70}, 600 
      ); 

      return false; 
     }); 
    } 
} 
}); 

「M滾動而不是整個頁面,但類容器-1-只有某些DIV 2。

我遇到的問題是,當錨鏈接被點擊時,它會滾動到指定的ID,但是當我再次單擊相同的鏈接時,它會滾動到頂部。只是不知道如何防止再次滾動到頂部並保持靜止。

+0

嘗試動畫僅''(html,body)'?這一切似乎從乍一看來。 – Shikkediel

+0

我試過了,滾動根本不起作用。 –

+0

你可以顯示HTML嗎?更容易看到現場測試案例的情況。 – Shikkediel

回答

1

我找到了解決方案。

$(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) { 
      $('.content-container').animate({ 
       scrollTop: $('.content-container').scrollTop() + target.offset().top - 70 
      }, 1000); 
     return false; 
     } 
    } 
    }); 
});