WEB/jQuery

[jQuery] ์Šคํฌ๋กค ์ด๋ฒคํŠธ : ํ”„๋กœ์„ธ์Šค ๋ฐ” ๋งŒ๋“ค๊ธฐ

developer of the night sky 2023. 10. 16. 11:36

๐Ÿ”ป์Šคํฌ๋กค ์œ„์น˜์— ๋”ฐ๋ฅธ ํ”„๋กœ์„ธ์Šค ๋ฐ” ๋งŒ๋“ค๊ธฐ

 

๊ธฐ๋ณธ ๋ผˆ๋Œ€

์—๋ฐ‹์œผ๋กœ ์ž‘์„ฑํ•˜์—ฌ ์Šคํฌ๋กค์„ ํ•  ์ˆ˜ ์žˆ์„๋งŒํผ ๋ณธ๋ฌธ ๋‚ด์šฉ์„ ์ถ”๊ฐ€ํ•œ๋‹ค.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ex10.html</title>

    <style>
        #bar{
            width: 50%;
            height: 7px;
            background-color: tomato;
            position: fixed;
            left: 0;
            top: 0;
        }

    </style>

</head>
<body>
    <div id="bar"></div>
    <h1>Lorem ipsum dolor sit amet.</h1>    

    <!-- (p>lorem100)*30 -->

    <script src="../asset/js/jquery-1.12.4.js"></script>

</body>
</html>

 

์ด๋ฒคํŠธ

DOM์—์„œ๋Š” window.scrollY๋กœ ์Šคํฌ๋กค์˜ ์œ„์น˜๋ฅผ ํ™•์ธํ–ˆ๋‹ค.

jQuery์—์„œ๋Š” $(document).scrollTop()๋กœ ์Šคํฌ๋กค์˜ ์œ„์น˜๋ฅผ ํ™•์ธํ•œ๋‹ค.

 

์Šคํฌ๋กค๋ฐ” ์œ„์น˜์— ๋”ฐ๋ฅธ ํ”„๋กœ์„ธ์Šค๋ฐ” ํฌ๊ธฐ๋ฅผ ๊ตฌํ•˜๊ธฐ ์œ„ํ•ด ๋‘˜์˜ ๊ด€๊ณ„๋ฅผ ์‚ดํŽด๋ณด๋ฉด, ๋ฌธ์„œ์˜ ์„ธ๋กœ ๊ธธ์ด์˜ ์ตœ๋Œ€ ์œ„์น˜์ผ ๋•Œ, ํ”„๋กœ์„ธ์Šค๋ฐ”์˜ ํฌ๊ธฐ๊ฐ€ 100%๊ฐ€ ๋œ๋‹ค.

์ด๊ฒƒ์„ 1์ฐจ ๋ฐฉ์ •์‹์œผ๋กœ ๊ตฌํ•˜๋ฉด ์•„๋ž˜์™€ ๊ฐ™์€ ์‹์ด ๋‚˜์˜จ๋‹ค.
์Šคํฌ๋กค๋ฐ” ์ตœ๋Œ€ ์œ„์น˜ : 100% = ์Šคํฌ๋กค๋ฐ” ์œ„์น˜ : x

let x = $(document).scrollTop() * 100 / ($(document).outerHeight()-$(window).outerHeight());

x์˜ ๊ฐ’์„ ๊ตฌํ•˜์—ฌ bar์˜ ๋„ˆ๋น„๋กœ ์ง€์ •ํ•œ๋‹ค.

 

    <script>
        $(document).scroll(function() {
            // console.log($(document).scrollTop());

            let x = $(document).scrollTop() * 100 / ($(document).outerHeight()-$(window).outerHeight());

            $('#bar').css('width', x+'%');
        });
    </script>