2012-11-08 3 views
2

나는 별도의 페이지에있는 특정 게시물로 내 웹 사이트를 스크롤하려고합니다. 그러나이 부분 뒤에있는 PHP 부분을 사용하여 앵커를 생성했지만 JS 부분이 붙어 있습니다. 웹 페이지를 0,0 위치에서 시작한 다음 정적 앵커 태그로 이동했습니다. 내가 고민하는 것은 JS가 현재 URL에서 앵커 태그를 가져온 다음 짧은 지연 후에 주어진 태그로 부드럽게 스크롤되도록하는 방법이다. 내가 URL 오프 앵커 태그를 가져 오는 다음 잘린 발견지연 후 JS 스크롤

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

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

하지만 난이 일부 지연 후 실행할 수있는 방법을 잘 모르겠어요 :

내 현재 코드입니다.

$(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 []; 
     } 

    }); 

답변

0

내가 CSS-Tricks forum에서 발견 조각을 사용하여 내 문제를 해결하기 위해 관리. 페이지로드시 앵커 태그로 스크롤합니다. 항상 맨 위부터 시작합니다.

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

setTimeout은 문자열로 전달 된 이전 코드를 허용하지 않으며 함수 이름 만 허용한다고 생각합니다. 대신 익명 함수를 사용해보십시오 :

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

+1

setTimeout/Interval에 문자열을 전달하는 것은 유효하고 효과적입니다. 단지 좋은 습관이 아닙니다. 'setTimeout ("alert ('Hello!')", 1000);' – Stecman

+0

오, 이상한. 자바 스크립트가 이상합니다. – sgroves

+0

내가 지금 가지고있는 코드는 사실 작동하지만, 당신 코드도 마찬가지입니다. 그러나 부드럽게 스크롤하는 효과를 얻기 위해 노력하고 있습니다. 주로 JS 지식이 상당히 제한되어 있기 때문에 이전에 언급 한 두 조각을 어떻게 연결해야할지 모릅니다. – Ninetou