开发者

How to smoothly scroll a browser window using hashes with a fixed element on top?

I have a website that has a fixed navigation bar at the top that contains links to achors in the rest of the content like so:

<header style="position:fixed">
  <a href="#hello">Scroll to Headline Hello</a>
</header>
<article>
  <h1><a name="hello" id="hello">Hello</a><h1>
</article>

When someone clicks on the link, the corresponding headline is obscured by the header, because the browser positions it directly at the beginning of the viewport. I tried to use the csstricks' jQuery-script described here http://css-tricks.com/snippets/jquery/smooth-scrolling/ to smootly scroll to a targetOffset + heightOfHeader but that just makes the content jump randomly up and down.

Here is the script:

$(document).ready(function() {
  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;
        $(this).click(function(event) {
          event.preventDefault();
          $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
            location.hash = target;
          });
        });
      }
    }
  });

  // use the first element that is "scrollable"
  function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
      var el = arguments[i],
          $scrollElement = $(el);
   开发者_Go百科   if ($scrollElement.scrollTop()> 0) {
        return el;
      } else {
        $scrollElement.scrollTop(1);
        var isScrollable = $scrollElement.scrollTop()> 0;
        $scrollElement.scrollTop(0);
        if (isScrollable) {
          return el;
        }
      }
    }
    return [];
  }

});

Any help would be appreciated.


I see that you're tagging the question with jquery. I like to use scrollTo plugin to accomplish this.

http://flesler.blogspot.com/2007/10/jqueryscrollto.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜