如果页面高度动态更改,则与 id 的链接不起作用



我正在处理的结构如下:

<html>
    <header>
         <a href="#footer">scroll to footer</a>
    </header>
    <section id="gallery"></section>
    <footer id="footer"></footer>
</html>

很明显,我希望在点击链接时滚动到#footer,但问题是#gallery是在页面加载后加载的,整个页面的高度会发生变化。链接仅滚动到加载#gallery之前#footer所在的位置。

我使用的图库示例:http://tympanus.net/Development/GammaGallery/

我用来平滑滚动的jQuery代码:

$(document).ready(function() {
  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) {
         var targetOffset = $target.offset().top;
         $(this).click(function() {
           $('html, body').animate({scrollTop: targetOffset}, 600);
           return false;
         });
      }
    }
  });
});

当事件处理程序函数被调用时,只需将targetOffset赋值放在函数中即可获得.offset()

$(this).click(function() {
    var targetOffset = $target.offset().top;
    $('html, body').animate({scrollTop: targetOffset}, 600);
    return false;
});

最新更新