programing tip

새로 고침시 자동 브라우저 스크롤 방지

itbloger 2020. 9. 11. 07:47
반응형

새로 고침시 자동 브라우저 스크롤 방지


페이지 a로 이동하여 스크롤 한 다음 새로 고침하면 페이지를 떠난 지점에서 새로 고침됩니다. 이것은 훌륭하지만 URL에 앵커 위치가있는 페이지에서도 발생합니다. 예를 들어 링크를 클릭하고 http://example.com/post/244#comment5주변을 둘러 본 후 페이지를 새로 고치면 앵커에 있지 않고 페이지가 점프합니다. 자바 스크립트로 이것을 방지하는 방법이 있습니까? 그래서 당신이 항상 앵커로 이동하는 것은 중요하지 않습니다.


이 솔루션은 브라우저 동작의 변경으로 인해 더 이상 권장되지 않습니다. 다른 답변을 참조하십시오.

기본적으로 앵커가 사용되면 창 스크롤 이벤트에 바인딩합니다. 첫 번째 스크롤 이벤트는 브라우저가 수행하는 자동 위치 조정에 속해야한다는 생각입니다. 이것이 발생하면 우리는 우리 자신의 위치를 ​​변경하고 바운드 이벤트를 제거합니다. 이는 후속 페이지 스크롤이 시스템을 지루하게하는 것을 방지합니다.

$(document).ready(function() {
    if (window.location.hash) { 
        //bind to scroll function
        $(document).scroll( function() {
            var hash = window.location.hash
            var hashName = hash.substring(1, hash.length);
            var element;

            //if element has this id then scroll to it
            if ($(hash).length != 0) {
                element = $(hash);
            }
            //catch cases of links that use anchor name
            else if ($('a[name="' + hashName + '"]').length != 0)
            {
                //just use the first one in case there are multiples
                element = $('a[name="' + hashName + '"]:first');
            }

            //if we have a target then go to it
            if (element != undefined) {
                window.scrollTo(0, element.position().top);
            }
            //unbind the scroll event
            $(document).unbind("scroll");
        });
    }

});

Chrome에서는 scrollTop을 0으로 강제 설정하더라도 첫 번째 스크롤 이벤트 이후에 점프합니다.

다음과 같이 스크롤을 바인딩해야합니다.

$(window).on('beforeunload', function() {
    $(window).scrollTop(0);
});

따라서 브라우저는 새로 고침 전 처음에 있다고 믿도록 속입니다.


자동 스크롤 복원을 비활성화하려면이 태그를 헤드 섹션에 추가하면됩니다.

<script>history.scrollRestoration = "manual"</script>

IE에서는 지원하지 않습니다. 브라우저 호환성.


After number of failures finally I managed to do the trick. anzo is correct here as using beforeunload will make the page jump to top when a user reloads the page or clicks a link. So unload is the clearly way to do this.

$(window).on('unload', function() {
   $(window).scrollTop(0);
});

Javascript way(Thanks ProfNandaa):

window.onunload = function(){ window.scrollTo(0,0); }

EDIT: 16/07/2015

The jump issue is still there with Firefox even with unload event.


You can just put a # at the end so the page will load at the top.

Works on all browsers, mobile and desktop, because it is so simple.

$(document).ready(function() {
var url = window.location.href;
console.log(url);
if( url.indexOf('#') < 0 ) {
    window.location.replace(url + "#");
} else {
    window.location.replace(url);
}

});

// This loads the page with a # at the end.


Here's a a more general approach. Instead of trying to prevent the browser from scrolling (or jumping to the top as it would look like) I just restore the previous position on the page. I.e. I'm recording the current y-offset of the page in localStorage and scroll to this position once the page has loaded.

function storePagePosition() {
  var page_y = window.pageYOffset;
  localStorage.setItem("page_y", page_y);
}


window.addEventListener("scroll", storePagePosition);


var currentPageY;

try {
  currentPageY = localStorage.getItem("page_y");

  if (currentPageY === undefined) {
    localStorage.setItem("page_y") = 0;
  }

  window.scrollTo( 0, currentPageY );
} catch (e) {
    // no localStorage available
}

You should be able to.

Onload, check if window.location.hash has a value. If it does, grab the element with an id that matches the hash value. Find the position of the element (recursive calls to offsetTop/offsetLeft) and then pass those values into the window.scrollTo(x, y) method.

This should scroll the page to the desired element.

참고URL : https://stackoverflow.com/questions/7035331/prevent-automatic-browser-scroll-on-refresh

반응형