본문 바로가기

HTML/Javascript 기초

[Javascript] 스크롤 위치 구하기

스크롤 위치 구하기

$대상.scrollLeft();
$대상.scrollTop();

 

스크롤 위치 설정하기

$대상.scrollLeft(위치값);
$대상.scrollTop(위치값);

 

setInterval 함수를 이용하여 스크롤을 이동시켜보자.

<!DOCTYPE html>
<html lang="ㅏㅐ">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>스크롤 위치 구하기</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            font-size: 9pt;
        }

        .nav {
            margin: 30px 0 0 50px;
        }

        #btn, #move {
            width: 50px;
            height: 30px;
        }

        #container {
            position: absolute;
            width: 300px;
            height: 200px;
            left: 50px;
            top: 100px;
            border: 1px solid #000;
            overflow: scroll;
        }

        img {
            width: 1000px;
        }
    </style>
    <script src="../../js/jquery-3.5.1.min.js"></script>
    <script>
        $(document).ready(function () {
            var $info = $("#info");
            var $container = $("#container");
            var strInfo = null;
            
            $("#btn").click(function () {
                strInfo = "scrollLeft=" + $container.scrollLeft() + "<br>";
                strInfo += "scrollTop=" + $container.scrollTop();
                $info.html(strInfo);
            })

            $("#move").click(function () {
                var left = $container.scrollLeft();
                var count = 0;
                var timerID = setInterval(function () {
                    left += 5;
                    $container.scrollLeft(left);
                    count++;
                    $info.html(count + ", left = " + left + ", scrollEnd = " + scrollEnd);
                    if (left >= scrollEnd) {
                        clearInterval(timerID);
                    }
                }, 100);
            });
        })
    </script>
</head>

<body>
    <div class="nav">
        <button id="btn">확인 </button>
        <button id="move">이동</button>
        <div id="info">
            여기에 스크롤 정보가 출력될 거에요.
        </div>
    </div>
    <div id="container">
        <img src="../../images/sample_img.png">
    </div>
</body>

</html>

 

 

728x90
반응형