문제

I'm trying to make my website scroll to specific post that is on separate page. I figured the PHP part behind this to generate anchors for me however I'm stuck with JS part. I managed to make webpage start at position 0,0 and then to go to static anchor tag. What I struggle with is how do I make JS fetch anchor tag from current URL and then make it smoothly scroll to given tag after short delay.

My current code is:

$(document).ready(function() {
    if (location.hash) {
        window.scrollTo(0, 0);
      }
});

setTimeout("window.location.hash = '#scroll';", 5000);

I found following snipped that fetches an anchor tag off URL but I'm not sure how can I make it execute after some delay.

    $(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);
          if ($scrollElement.scrollTop()> 0) {
            return el;
          } else {
            $scrollElement.scrollTop(1);
            var isScrollable = $scrollElement.scrollTop()> 0;
            $scrollElement.scrollTop(0);
            if (isScrollable) {
              return el;
            }
          }
        }
        return [];
      }

    }); 
도움이 되었습니까?

해결책 2

I managed to solve my problem using snippet that I found on CSS-Tricks forum. It scrolls to an anchor tag on page load, always starting from the very top of the page.

$(window).bind("ready", function() {
   var urlHash = window.location.href.split("#")[1];
    $('html,body').animate({scrollTop:$('a[href="#'+urlHash+'"]').offset().top}, 1500);        
});

다른 팁

I don't believe setTimeout accepts any old code passed as a string, only function names. Try using an anonymous function instead:

setTimeout(function() { window.location.hash = '#scroll'; }, 5000);

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top