스크롤 위치 설정


107

스크롤러가 맨 위로 스크롤되도록 페이지의 스크롤 위치를 설정하려고합니다.

나는 이와 같은 것이 필요하다고 생각하지만 작동하지 않습니다.

(function () { alert('hello'); document.body.scrollTop = 0; } ());

어떤 아이디어?

답변:



51

또한 주목할 가치가 있습니다 window.scrollBy(dx,dy)( ref )


1
이것은 매우 도움이되었다
Jeff82

34

전체 창 대신 요소를 스크롤하려는 경우 요소에는 scrollToscrollBy메서드 가 없습니다 . 다음을 수행해야합니다.

var el = document.getElementById("myel"); // Or whatever method to get the element

// To set the scroll
el.scrollTop = 0;
el.scrollLeft = 0;

// To increment the scroll
el.scrollTop += 100;
el.scrollLeft += 100;

기본적으로 지원하지 않는 브라우저 에서 웹 페이지의 모든 기존 HTML 요소에 window.scrollTowindow.scrollBy함수를 모방 할 수도 있습니다 .

Object.defineProperty(HTMLElement.prototype, "scrollTo", {
    value: function(x, y) {
        el.scrollTop = y;
        el.scrollLeft = x;
    },
    enumerable: false
});

Object.defineProperty(HTMLElement.prototype, "scrollBy", {
    value: function(x, y) {
        el.scrollTop += y;
        el.scrollLeft += x;
    },
    enumerable: false
});

그래서 당신은 할 수 있습니다 :

var el = document.getElementById("myel"); // Or whatever method to get the element, again

// To set the scroll
el.scrollTo(0, 0);

// To increment the scroll
el.scrollBy(100, 100);

참고 : Object.defineProperty에 속성을 직접 추가하는 prototype것은 나쁜 습관을 깨는 것이므로 권장됩니다 (보면 :-).


도움이되었습니다. 감사합니다. 그러나 요소에는 'scrollTo'메서드가 있음을 발견했습니다. 참조 developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo
Narvalex

@Narvalex는 두 번째 단락이 말하는 것입니다.
Jorge Fuentes González

내가 지적한 참조는 이러한 함수가 내장되어 있음을 보여줍니다. 내장 메서드의 속성을 정의 할 필요가 없습니다
Narvalex

@Narvalex 아, 방금 "없어"를 읽었습니다. 요즘에는 IE11과 같은 브라우저를 찾기가 어렵지만 모든 브라우저에이 기능이있는 것은 아닙니다.
Jorge Fuentes González

3

... 아니면 그냥 교체 body에 의해 documentElement:

document.documentElement.scrollTop = 0;
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.