div id jQuery로 부드럽게 스크롤


248

div id jquery 코드로 스크롤하여 올바르게 작동하려고했습니다. 다른 스택 오버플로 질문에 따라 다음을 시도했습니다.

데모 http://jsfiddle.net/kevinPHPkevin/8tLdq/

$('#myButton').click(function() {
   $.scrollTo($('#myDiv'), 1000);
});

그러나 작동하지 않았습니다. 그것은 단지 div에 스냅합니다. 나는 또한 시도했다

$('#myButton').click(function(event) {
     event.preventDefault();
   $.scrollTo($('#myDiv'), 1000);
});

진행하지 않고.



@TheVanillaThrilla 내가했지만 단일 링크로 사용하기에는 너무 부풀어 보였다
— StevenPHP

1
@StevenPHP, 나는 내 대답 stackoverflow.com/a/26129950/947687 에 따라 귀하의 예제에서 JavaScript 코드를 대체했습니다 . 그리고 그것은 jsfiddle.net/8tLdq/643 작동 합니다 .
— dizel3d September

OP는 오래되었지만 SE에서 온 다른 사람들을 위해이 게시물을 공유 할 것입니다. 다음 주 간단한 함수 문제를 해결한다는 기사입니다 smartik.ws/2015/01/...
— 앤드류 Surdu

답변:


667

당신은 애니메이션을해야합니다 html, body

데모 http://jsfiddle.net/kevinPHPkevin/8tLdq/1/

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#myDiv").offset().top
    }, 2000);
});

9
@vector 하나의 문제가 있습니다. 클릭하면 jquery와 싸워서 스크롤해야합니다. 어떤 솔루션입니까?
— YesItsMe

@yesitsme ... 내 경우에는 위 또는 아래로
— Gray Spectrum

@GraySpectrum up을 클릭하면 바로 지연되는 것처럼 들립니다.
— YesItsMe

1
같은 질문이 있습니다. 다른 위치로 스크롤 해야하는 버튼이 거의 없으면이 코드를 수정하려고 시도했지만 작동하지 않습니다. 다른 예를 들어 주시겠습니까?
— 드레드로드

그것에 대한 "수정"을 찾았습니다. 올바른 요소의 스크롤이 수정되었지만 동일한 "스크롤 대상"대상을 클릭하여 계속 위아래로 이동합니다. var target = $(this).data("target"); $(".basics-content").animate({scrollTop: $(target).offset().top}, 1000); });설명 : ID 번호를 제공하면서 .basics-content실제로 스크롤하려는 모달의 내부 div입니다. target의 요소 ...
— 롤랜드

111

부드러운 스크롤을 위해 HTML 마크 업을 변경하지 않고 페이지에서 표준 href-id 탐색 을 재정의 하려면 다음을 사용하십시오 ( 예 ).

// handle links with @href started with '#' only
$(document).on('click', 'a[href^="#"]', function(e) {
    // target element id
    var id = $(this).attr('href');

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

    // top position relative to the document
    var pos = $id.offset().top;

    // animated top scrolling
    $('body, html').animate({scrollTop: pos});
});

3
이것은 아주 잘 작동합니다. 아주 작은 조정 var pos = $(id).offset().top;이 가능할 수 있습니다.var pos = $id.offset().top;
— Davey

아주 좋아요 특정 링크에서만 이런 일이 일어나기를 원한다면 (예를 들어, 정보를 표시하거나 숨길 수있는) 클래스 이름을 추가하고 일치 선언의 끝에 클래스 이름 (스크롤러)을 붙입니다 (예 : a [href ^ = "#"]. scroller).
— Privateer

jQuery없이 어떻게합니까?
— Vadorequest

21

여기 내 2 센트가 있습니다 :

자바 스크립트 :

$('.scroll').click(function() {
    $('body').animate({
        scrollTop: eval($('#' + $(this).attr('target')).offset().top - 70)
    }, 1000);
});

HTML :

<a class="scroll" target="contact">Contact</a>

그리고 목표 :

<h2 id="contact">Contact</h2>

이 솔기는 doctype을 선언하지 않은 경우에만 작동합니다.
— David Martins

6
eval여기에 어떤 용도로 사용 됩니까?
— Seer

나는 그것이 필요합니다 생각 $('html, body').animate스크롤로
— 어 쉐드 칸을

6

내가 사용하는 것은 다음과 같습니다.

<!-- jquery smooth scroll to id's -->   
<script>
$(function() {
  $('a[href*=#]:not([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) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 500);
        return false;
      }
    }
  });
});
</script>

이것의 장점은 각각 새로운 스크립트를 실행할 필요없이 무제한의 해시 링크와 해당 ID를 사용할 수 있다는 것입니다.

WordPress를 사용하는 경우 테마 footer.php파일 앞에 코드를 닫기 본문 태그 바로 앞에 삽입하십시오 </body>.

테마 파일에 액세스 할 수없는 경우 게시물 / 페이지 편집기 (텍스트 모드에서 게시물을 편집해야 함) 또는 모든 페이지에로드되는 텍스트 위젯에 코드를 포함 할 수 있습니다.

다른 CMS를 사용하거나 HTML 만 사용하는 경우 닫는 body 태그 바로 앞에 모든 페이지에로드되는 섹션에 코드를 삽입 할 수 있습니다 </body>.

이것에 대한 자세한 내용이 필요하면 빠른 게시물을 확인하십시오 : jQuery smooth scroll to id

도움이 되길 바랍니다. 궁금한 점이 있으면 알려주세요.


이것이 얼마나 간단하고 바닐라인지를 사랑합니다.
— DoPeT

5

한 가지 예 더 :

HTML 링크 :

<a href="#featured" class="scrollTo">Learn More</a>

JS :

  $(".scrollTo").on('click', function(e) {
     e.preventDefault();
     var target = $(this).attr('href');
     $('html, body').animate({
       scrollTop: ($(target).offset().top)
     }, 2000);
  });

HTML 앵커 :

  <div id="featured">My content here</div>

3

jQuery scrollTo 플러그인 파일을로드 하시겠습니까?

콘솔에서 "scrollTo"오류를 찾을 수없는 개체가 있습니다.

scrollTO 메소드는 기본 jquery 메소드가 아닙니다. 그것을 사용하려면 jquery scroll To 플러그인 파일을 포함시켜야합니다.

심판 : http://flesler.blogspot.in/2009/05/jqueryscrollto-142-released.html http://flesler.blogspot.in/2007/10/jqueryscrollto.html

soln : 이것을 head 섹션에 추가하십시오.

<script src="\\path\to\the\jquery.scrollTo.js file"></script>

이것은 받아 들여진 대답이어야합니다. 질문의 코드가 정확하고 잘 작동합니다. scrollTo 플러그인이 작동하지 않거나 작동하지 않는 것 같습니다. . 그는 비슷한 일을하는 다른 방법에 대해 묻지 않았습니다.
— Chris Kavanagh

3

이 스크립트는 Vector의 스크립트를 개선 한 것입니다. 나는 그것에 약간 변경했습니다. 따라서이 스크립트는 클래스 페이지 스크롤이있는 모든 링크에서 작동합니다.

처음에는 쉬지 않고 :

$("a.page-scroll").click(function() {
    var targetDiv = $(this).attr('href');
    $('html, body').animate({
        scrollTop: $(targetDiv).offset().top
    }, 1000);
});

완화를 위해 Jquery UI가 필요합니다.

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

이것을 스크립트에 추가하십시오 :

'easeOutExpo'

결정적인

$("a.page-scroll").click(function() {
    var targetDiv = $(this).attr('href');
    $('html, body').animate({
        scrollTop: $(targetDiv).offset().top
    }, 1000, 'easeOutExpo');
});

당신이 찾을 수있는 모든 여유 : 치트 시트 .


3

이 코드는 웹의 모든 내부 링크에 유용합니다

    $("[href^='#']").click(function() {
        id=$(this).attr("href")
        $('html, body').animate({
            scrollTop: $(id).offset().top
        }, 2000);
    });


1

다음과 같은 간단한 jQuery 코드를 사용하면됩니다.

튜토리얼, 데모 및 소스 코드는 여기에서 찾을 수 있습니다 -jQuery를 사용하여 div로 부드럽게 스크롤

자바 스크립트 :

$(function() {
    $('a[href*=#]:not([href=#])').click(function() {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.substr(1) +']');
        if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top
            }, 1000);
            return false;
        }
    });
});

HTML :

<a href="#section1">Go Section 1</a>
<div id="section1">
    <!-- Content goes here -->
</div>

1

여기서 나는 이것을 시도했다.

$('a[href*="#"]').on('click', function (e) {
    e.preventDefault();

    $('html, body').animate({
        scrollTop: $($(this).attr('href')).offset().top
    }, 500, 'linear');
});

HTML :

 <a href="#fast-food" class="active" data-toggle="tab" >FAST FOOD</a>

<div id="fast-food">
<p> Scroll Here... </p>
  </div>

답변에서 다른 점은 무엇입니까?
— yunandtidus


0

이것은 나에게 효과적입니다.

<div id="demo">
        <h2>Demo</h2>
</div>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
    $(document).ready(function () {
        // Handler for .ready() called.
        $('html, body').animate({
            scrollTop: $('#demo').offset().top
        }, 'slow');
    });
</script>

감사.


0

고정 된 헤더가있어 그 아래로 스크롤되지 않는 경우 jQuery를 사용하여 div / anchor로 부드럽게 스크롤하는 솔루션이 있습니다. 다른 페이지에서 링크하면 작동합니다.

".site-header"를 헤더가 포함 된 div로 바꾸십시오.

$(function() {

$('a[href*="#"]:not([href="#"])').click(function() {
var headerheight = $(".site-header").outerHeight();
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) {
    $('html, body').animate({
      scrollTop: (target.offset().top - headerheight)
    }, 1000);
    return false;
  }
}
});

//Executed on page load with URL containing an anchor tag.
if($(location.href.split("#")[1])) {
var headerheight = $(".site-header").outerHeight();
  var target = $('#'+location.href.split("#")[1]);
  if (target.length) {
    $('html,body').animate({
      scrollTop: target.offset().top - headerheight
    }, 1);
    return false;
  }
}
});
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.