2015-04-22 91 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; 
     } 
    } 
    }); 
});