Language

HTML + CSS/JQuery

JQuery - 버튼 클릭시 스크롤 이동

초코렛맛 2024. 7. 10. 11:25

  버튼 클릭시 스크롤 이동

<style>

    .container {
        height: 100%;
        width: 100%;
    }
    .section {
        height: 100vh;
        width: 100%;
    }
    .section:nth-child(2n) {
        background-color: rgb(184, 212, 185);
    }
    .section:nth-child(2n+1) {
        background-color: #f08bdf;
    }
    .menu{
        display: flex;
        position: fixed;
        top: 5%;
        right: 10%;
        gap: 5%;
    }
    .menu > .s{
        width: 40px;
        height: 40px;
        font-size: 20px;
        cursor: pointer;
        background-color: #fff;
        text-align: center;
        align-content: center;
        line-height: 20px;
        border-radius: 20%;
    }
</style>

<body>
    <div class="container">
        <div class="section">Section 1</div>
        <div class="section">Section 2</div>
        <div class="section">Section 3</div>
        <div class="section">Section 4</div>
    </div>
    <div class="menu">
        <div class="s">1</div>
        <div class="s">2</div>
        <div class="s">3</div>
        <div class="s">4</div>
    </div>
    <script>
        $(function(){            
            $(".s").click(
                function(){
                    let i = $(this).index();
                    let t = $(".section").eq(i).offset().top;
                    $("html").stop().animate({scrollTop:t},1000);                   
                }
            );

        });
    </script>
</body>

 

 

  스크롤 확인 후 클래스 추가

<style>
    main{
        height: 5000px;
        background-color: red;
    }
    .ab{
        background-color: salmon;
    }
    .conts1{
        height: 600px;
    }
    .conts2{
        height: 300px;
    }
    .button{
        width: 120px;
        height: 40px;
        position: sticky;
        background-color: #fff;
        top: 0;
        cursor: pointer;
    }
</style>
<body>
    <main>
        <div class="button">버튼</div>
        <div class="conts1">1</div>
        <div class="conts2">2</div>
    </main>
    <script>
        $(function(){
            let mbgc = $("main").css("background-color");
            let wst;
            let c2t;
            $(window).scroll(function(){
                wst = $(window).scrollTop();
                c2t = $(".conts2").offset().top;
                if(wst>=c2t){
                    $("main").addClass("ab");
                }
                else{
                    $("main").removeClass("ab");
                }
                console.log(wst+"  "+c2t);
            });
            $(".button").click(function(){
                $("html").stop().animate({scrollTop:c2t},1000);
            });
        });
    </script>
</body>