IT story

스크롤 위치 설정

hot-time 2020. 9. 6. 12:02
반응형

스크롤 위치 설정


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

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

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

어떤 아이디어?


다음 window.scrollTo()과 같이 사용할 수 있습니다 .

window.scrollTo(0, 0); // values are x,y-offset

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


전체 창 대신 요소를 스크롤하려는 경우 요소에는 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것은 나쁜 습관을 깨는 것이므로 권장됩니다 (보면 :-).

참고 URL : https://stackoverflow.com/questions/4192847/set-scroll-position

반응형