스크롤 상단 이동 버튼에... 자바스크립트 질문 드립니다. 채택완료
버튼에 페이지의 상단과 하단을 %로 표시되게 해놓은 상태입니다.
데스크탑에서는 마우스로 스크롤 하면 제대로 100%가 표시가 되는데...
모바일 기기에서 하단까지 스크롤을 내리면 100% 표시가 되지 않고 80~90% 쯤에서 멈추네요...
Copy
$(function() {
function updateScrollPercent() {
var docHeight = $(document).height();
var windowHeight = $(window).height();
var scrollPosition = $(window).scrollTop();
if (scrollPosition === 0) {
$('#top_btn').hide();
return;
}
if (docHeight > windowHeight) {
var scrollPercent = (scrollPosition / (docHeight - windowHeight)) * 100;
var scrollPercentRounded = Math.round(scrollPercent);
$('#top_btn').text(scrollPercentRounded + '%').show();
$('#top_btn').css('background', 'rgba(48, 89, 199, ' + (scrollPercentRounded / 100) + ')');
} else {
$('#top_btn').hide();
}
}
$(window).on('scroll', function() {
window.requestAnimationFrame(updateScrollPercent);
});
updateScrollPercent();
$("#top_btn").on("click", function() {
$("html, body").animate({ scrollTop: 0 }, '500');
return false;
});
$("#top_btn").hover(
function() {
$(this).text('Top');
},
function() {
if ($(this).is(':visible')) {
updateScrollPercent();
}
}
);
});
답변 2개
채택된 답변
+20 포인트
2년 전
Copy
// var windowHeight = $(window).height();
var windowHeight = window.visualViewport.height;
로그인 후 평가할 수 있습니다
답변에 대한 댓글 1개
댓글을 작성하려면 로그인이 필요합니다.
2년 전
Copy
$(function () {
function updateScrollPercent() {
var docHeight = $(document).height();
var windowHeight = window.innerHeight;
var scrollPosition = window.scrollY;
if (scrollPosition === 0) {
$('#top_btn').hide();
return;
}
if (docHeight > windowHeight) {
var scrollPercent = (scrollPosition / (docHeight - windowHeight)) * 100;
var scrollPercentRounded = Math.round(scrollPercent);
$('#top_btn').text(scrollPercentRounded + '%').show();
$('#top_btn').css('background', 'rgba(48, 89, 199, ' + (scrollPercentRounded / 100) + ')');
} else {
$('#top_btn').hide();
}
}
window.onscroll = function () {
window.requestAnimationFrame(updateScrollPercent);
};
updateScrollPercent();
$("#top_btn").on("click", function () {
$("html, body").animate({ scrollTop: 0 }, '500');
return false;
});
$("#top_btn").hover(
function () {
$(this).text('Top');
},
function () {
if ($(this).is(':visible')) {
updateScrollPercent();
}
}
);
});
로그인 후 평가할 수 있습니다
답변에 대한 댓글 1개
2년 전
늦게 봤네요 ㅠ 깜박 잠들어서.. ㅎ
주신 코드 적용 해보니 하단을 두번? 스크롤을 내리니 %값이 조정되네요
답변 감사합니다.
주신 코드 적용 해보니 하단을 두번? 스크롤을 내리니 %값이 조정되네요
답변 감사합니다.
댓글을 작성하려면 로그인이 필요합니다.
답변을 작성하려면 로그인이 필요합니다.
로그인