스크롤 상단 이동 버튼에... 자바스크립트 질문 드립니다.

매출이 오르면 내리는 수수료! 지금 수수료센터에서 전자결제(PG)수수료 비교견적 신청해 보세요!
스크롤 상단 이동 버튼에... 자바스크립트 질문 드립니다.

QA

스크롤 상단 이동 버튼에... 자바스크립트 질문 드립니다.

답변 2

본문

버튼에 페이지의 상단과 하단을 %로 표시되게 해놓은 상태입니다.

데스크탑에서는 마우스로 스크롤 하면 제대로 100%가 표시가 되는데...

모바일 기기에서 하단까지 스크롤을 내리면 100% 표시가 되지 않고 80~90% 쯤에서 멈추네요...


$(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


        // var windowHeight = $(window).height();
        var windowHeight = window.visualViewport.height;

$(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();
            }
        }
    );
});
답변을 작성하시기 전에 로그인 해주세요.
QA 내용 검색
질문등록
전체 0
© SIRSOFT
현재 페이지 제일 처음으로