Program Tip

jQuery scrollTop은 Chrome에서 작동하지 않지만 Firefox에서는 작동합니다.

programtip 2020. 10. 11. 11:15
반응형

jQuery scrollTop은 Chrome에서 작동하지 않지만 Firefox에서는 작동합니다.


scrollTop맨 위로 이동하기 위해 jQuery 기능을 사용 했지만 이상하게도 '부드러운 애니메이션 스크롤'이 약간 변경 한 후 Safari 및 Chrome에서 작동하지 않습니다 (부드러운 애니메이션없이 스크롤).

그러나 Firefox에서는 여전히 원활하게 작동합니다. 무엇이 잘못 되었을까요?

다음은 내가 사용한 jQuery 함수입니다.

jQuery :

$('a#gotop').click(function() {
    $("html").animate({ scrollTop: 0 }, "slow");
    //alert('Animation complete.');
    //return false;
});

HTML

<a id="gotop" href="#">Go Top </a>

CSS

#gotop {
      cursor: pointer;
      position: relative;
      float: right;
      right: 20px;
      /*top:0px;*/
}

사용해보십시오 $("html,body").animate({ scrollTop: 0 }, "slow");

이것은 크롬에서 나를 위해 작동합니다.


CSS html요소에 다음 overflow마크 업 있으면 scrollTop작동하지 않습니다.

html {
    overflow-x: hidden;
    overflow-y: hidden;
}

scrollTop스크롤 을 허용하려면 마크 업을 수정하여 요소 overflow에서 마크 업을 제거 하고 html요소에 추가하십시오 body.

body { 
    overflow-x: hidden;
    overflow-y: hidden;
}

'document'와 함께 scrollTop ()을 사용하면 두 브라우저에서 모두 작동합니다.

$(document).scrollTop();

... 'html'또는 'body'대신. 그렇지 않으면 두 브라우저에서 동시에 작동하지 않습니다.


나는 이것을 Chrome, Firefox 및 Safari에서 성공적으로 사용했습니다. 아직 IE에서 테스트 할 수 없었습니다.

if($(document).scrollTop() !=0){
    $('html, body').animate({ scrollTop: 0 }, 'fast');
}

"if"문을 사용하는 이유는 사용자가 사이트 상단에서 모두 준비되었는지 확인하기 위해서입니다. 그렇다면 애니메이션을 수행하지 마십시오. 이렇게하면 화면 해상도에 대해별로 걱정할 필요가 없습니다.

내가 $(document).scrollTop대신 사용 하는 이유 . $('html,body')Chrome은 어떤 이유로 항상 0을 반환하기 때문입니다.


본문을 스크롤하고 작동하는지 확인하십시오.

function getScrollableRoot() {
    var body = document.body;
    var prev = body.scrollTop;
    body.scrollTop++;
    if (body.scrollTop === prev) {
        return document.documentElement;
    } else {
        body.scrollTop--;
        return body;
    }
}


$(getScrollableRoot()).animate({ scrollTop: 0 }, "slow");

$("html, body").animate두 개가 아닌 하나의 애니메이션 만 사용했기 때문에이 방법 이 더 효율적 입니다. 따라서 두 개가 아니라 하나의 콜백 만 실행됩니다.


크롬에서 스크롤하는 것과 같은 문제가 있습니다. 그래서 내 스타일 파일에서이 코드 줄을 제거 했습니다.

html{height:100%;}
body{height:100%;}

이제 스크롤로 재생할 수 있으며 작동합니다.

var pos = 500;
$("html,body").animate({ scrollTop: pos }, "slow");

아마도 당신은 의미 top: 0

$('a#gotop').click(function() {
  $("html").animate({ top: 0 }, "slow", function() { 
                                           alert('Animation complete.'); });
  //return false;
});

에서 애니메이션의 문서

.animate ( properties , [duration], [easing], [callback])
properties 애니메이션이 이동하는 CSS 속성 맵입니다.
...

또는 $(window).scrollTop()?

$('a#gotop').click(function() {
  $("html").animate({ top: $(window).scrollTop() }, "slow", function() { 
                                                              alert('Animation complete.'); });
  //return false;
});

// if we are not already in top then see if browser needs html or body as selector
var obj = $('html').scrollTop() !== 0 ? 'html' : 'body';

// then proper delegate using on, with following line:
$(obj).animate({ scrollTop: 0 }, "slow");

그러나 가장 좋은 방법은 네이티브 API를 사용하여 ID를 뷰포트로 스크롤하는 것입니다 (어쨌든 맨 위로 스크롤하기 때문에 이것은 외부 div 일 수 있습니다).

document.getElementById('wrapperIDhere').scrollIntoView(true);

나는 사용한다:

var $scrollEl = $.browser.mozilla ? $('html') : $('body');

jQuery scrollTop이 Chrome에서 작동하지 않지만 Firefox에서 작동 하기 때문에


이 문제를 해결하는 더 좋은 방법은 다음과 같은 함수를 사용하는 것입니다.

function scrollToTop(callback, q) {

    if ($('html').scrollTop()) {
        $('html').animate({ scrollTop: 0 }, function() {
            console.log('html scroll');
            callback(q)
        });
        return;
    }

    if ($('body').scrollTop()) {
        $('body').animate({ scrollTop: 0 }, function() {
            console.log('body scroll');
            callback(q)
        });
        return;
    }

    callback(q);
}

이것은 모든 브라우저에서 작동하며 FireFox가 두 번 스크롤되는 것을 방지합니다 (허용 된 답변-을 사용하는 경우 발생합니다 $("html,body").animate({ scrollTop: 0 }, "slow");).


Chrome, Firefox 및 Edge에서 테스트하는 동안 잘 작동 한 유일한 솔루션은 다음과 같이 Aaron 솔루션과 함께 setTimeout을 사용하는 것입니다.

setTimeout( function () {
    $('body, html').stop().animate({ scrollTop: 0 }, 100);
}, 500);

다른 솔루션 중 어느 것도 Chrome 및 Edge에서 페이지를 다시로드 할 때 이전 scrollTop을 재설정하지 않았습니다. 불행히도 Edge에는 여전히 약간의 "플릭"이 있습니다.


그래서 나도이 문제가 있었고이 함수를 작성했습니다.

/***Working function for ajax loading Start*****************/
function fuweco_loadMoreContent(elmId/*element ID without #*/,ajaxLink/*php file path*/,postParameterObject/*post parameters list as JS object with properties (new Object())*/,tillElementEnd/*point of scroll when must be started loading from AJAX*/){
	var	
		contener = $("#"+elmId),
		contenerJS = document.getElementById(elmId);
	if(contener.length !== 0){
		var	
			elmFullHeight = 
				contener.height()+
				parseInt(contener.css("padding-top").slice(0,-2))+
				parseInt(contener.css("padding-bottom").slice(0,-2)),
			SC_scrollTop = contenerJS.scrollTop,
			SC_max_scrollHeight = contenerJS.scrollHeight-elmFullHeight;
		if(SC_scrollTop >= SC_max_scrollHeight - tillElementEnd){
			$("#"+elmId).unbind("scroll");
			$.post(ajaxLink,postParameterObject)
			 .done(function(data){
			 	if(data.length != 0){
					$("#"+elmId).append(data);
					$("#"+elmId).scroll(function (){
						fuweco_reloaderMore(elmId,ajaxLink,postParameterObject);
					});
				}
			 });
		}
	}
}
/***Working function for ajax loading End*******************/
/***Sample function Start***********************************/
function reloaderMore(elementId) {
	var
		contener = $("#"+elementId),
		contenerJS = document.getElementById(elementId)
	;

    if(contener.length !== 0){
    	var
			elmFullHeight = contener.height()+(parseInt(contener.css("padding-top").slice(0,-2))+parseInt(contener.css("padding-bottom").slice(0,-2))),
			SC_scrollTop = contenerJS.scrollTop,
			SC_max_scrollHeight = contenerJS.scrollHeight-elmFullHeight
		;
		if(SC_scrollTop >= SC_max_scrollHeight - 200){
			$("#"+elementId).unbind("scroll");
			$("#"+elementId).append('<div id="elm1" style="margin-bottom:15px;"><h1>Was loaded</h1><p>Some text for content. Some text for content. Some text for content.	Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content.</p></div>');
			$("#"+elementId).delay(300).scroll(function (){reloaderMore(elementId);});
		}
    }
}
/***Sample function End*************************************/
/***Sample function Use Start*******************************/
$(document).ready(function(){
	$("#t1").scrollTop(0).scroll(function (){
		reloaderMore("t1");
    });
});
/***Sample function Use End*********************************/
.reloader {
    border: solid 1px red;
    overflow: auto;
    overflow-x: hidden;
    min-height: 400px;
    max-height: 400px;
    min-width: 400px;
    max-width: 400px;
    height: 400px;
    width: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
	<div class="reloader" id="t1">
		<div id="elm1" style="margin-bottom:15px;">
			<h1>Some text for header.</h1>
			<p>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
			</p>
		</div>
		<div id="elm2" style="margin-bottom:15px;">
			<h1>Some text for header.</h1>
			<p>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
			</p>
		</div>
		<div id="elm3" style="margin-bottom:15px;">
			<h1>Some text for header.</h1>
			<p>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
				Some text for content.<br>
			</p>
		</div>		
	</div>

다른 프로그래머에게 도움이 되길 바랍니다.


If it work all fine for Mozilla, with html,body selector, then there is a good chance that the problem is related to the overflow, if the overflow in html or body is set to auto, then this will cause chrome to not work well, cause when it is set to auto, scrollTop property on animate will not work, i don't know exactly why! but the solution is to omit the overflow, don't set it! that solved it for me! if you are setting it to auto, take it off!

if you are setting it to hidden, then do as it is described in "user2971963" answer (ctrl+f to find it). hope this is useful!


 $("html, body").animate({ scrollTop: 0 }, "slow");

This CSS conflict with scroll to top so take care of this

 html, body {
         overflow-x: hidden;        
    }

I don't think the scrollTop is a valid property. If you want to animate scrolling, try the scrollTo plugin for jquery

http://plugins.jquery.com/project/ScrollTo

참고URL : https://stackoverflow.com/questions/3042651/jquery-scrolltop-not-working-in-chrome-but-working-in-firefox

반응형