programing

jQuery scrollTopChrome에서는 작동하지 않지만 Firefox에서는 작동합니다.

instargram 2023. 10. 19. 21:52
반응형

jQuery scrollTopChrome에서는 작동하지 않지만 Firefox에서는 작동합니다.

나는 a를 사용한적이 있습니다.scrollTopjQuery에서 상단으로 이동하는 기능을 하지만 이상하게도 '매끄러운 애니메이션 스크롤'은 제가 몇 가지 변경을 한 후 사파리와 크롬(매끄러운 애니메이션 없이 스크롤)에서 작동을 멈췄습니다.

하지만 파이어폭스에서는 여전히 원활하게 작동하고 있습니다.뭐가 잘못됐나요?

여기 제가 사용했던 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요소와 a에 부가.body요소.

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

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

$(document).scrollTop();

...'html' 혹은 '몸'의 instead.그렇지 않으면 두 브라우저에서 동시에 작동하지 않습니다.

크롬, 파이어폭스, 사파리 등에서 성공적으로 사용했습니다.아직 IE에서 테스트를 하지 못했습니다.

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

"if" 문을 여는 이유는 사용자가 사이트 상단에 모두 준비되어 있는지 확인하기 위함입니다.그렇다면 애니메이션은 하지 마세요.그렇게 하면 화면 해상도에 대해 크게 걱정할 필요가 없습니다.

내가 사용하는 이유$(document).scrollTop를 들면 대신에$('html,body')크롬은 어떤 이유에서인지 항상 0을 반환하기 때문입니다.

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

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

이제 스크롤을 사용하여 재생할 수 있으며 작동합니다.

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

본문을 스크롤하고 작동했는지 확인합니다.

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애니메이션은 2개가 아니라 1개만 사용했기 때문입니다.따라서 콜백은 2발이 아니라 1발만 발사됩니다.

아마도 당신 말은top: 0

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

동물 문서로 부터

.animate ( 속성, [기간], [완화], [콜백 ] )
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를 뷰포트로 스크롤하는 것입니다(어쨌든 위로 스크롤하기 때문에 이는 당신의 외부 디브일 수 있습니다).

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);

페이지를 다시 로드할 때 다른 솔루션 중 아무도 이전 스크롤톱을 크롬과 엣지로 재설정하지 않았습니다.불행하게도 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>

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

만약 모질라가 html, body selector로 잘 작동한다면 문제가 오버플로와 관련되어 있을 가능성이 높습니다. html이나 body의 오버플로가 auto로 설정되어 있다면 크롬이 잘 작동하지 않을 것입니다. auto로 설정되어 있을 때 애니메이션의 scrollTop 속성이 작동하지 않을 것이기 때문입니다. 그러나 해결책은 너무 많습니다.오버플로우를 없애주세요. 설정하지 마세요! 해결해 주었습니다! 자동으로 설정하는 경우에는 해제하십시오!

숨김으로 설정하는 경우 "user2971963" 답변에 설명된 대로 수행합니다(찾으려면 ctrl+f).이것이 유용하기를 바랍니다!

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

이 CSS는 스크롤이 상단으로 충돌하므로 이 문제를 처리하십시오.

 html, body {
         overflow-x: hidden;        
    }

저는 제 CSS가 문제라는 것을 알았습니다.이것을 제 스타일시트에서 제거했는데 잘 작동했습니다.

*{scroll-behavior: smooth;}

스크롤 탑이 유효한 속성이 아닌 것 같습니다.스크롤을 애니메이션으로 만들고 싶다면 스크롤 To 플러그인에서 jquery를 시도해 보십시오.

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

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

반응형