본문 바로가기
프론트엔드 개발자/JS

자바스크립트 javascript 12. (4) 클릭하면 해당페이지로 넘어가는 이벤트 발생하기 (2) 업그레이드편

by 신디블로그 2023. 4. 13.
SMALL
 <style>

        * {
            margin:0;
            padding:0;
        }

        .box {
            height: 1000px;
            font-size: 100px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .box:nth-child(odd) {
            background-color: #fc0;
        }
        .box:nth-child(even) {
            background-color: #f20;
        }


        .top {
            position: fixed;
            right:100px;
            bottom:100px;
            width: 100px;
            height: 100px;
            background-color: #000;
            color:#fff;
        }

        .menu {
            position: fixed ;
            left:100px;
            top:100px;
            z-index: 100;
            font-size: 30px;
        }
    </style>
</head>
<body>
    <div class="box" id="box1">Page1</div>
    <div class="box" id="box2">Page2</div>
    <div class="box" id="box3">Page3</div>
    <div class="box" id="box4">Page4</div>
    <a href="#" class="top">위로가기</a>
    <ul class="menu">
        <li><a href="#box1" class="btn1">page1</a></li>
        <li><a href="#box2" class="btn2">page2</a></li>
        <li><a href="#box3" class="btn3">page3</a></li>
        <li><a href="#box4" class="btn4">page4</a></li>
    </ul>

    <script src="jquery/jquery-3.6.4.min.js"></script>
    <script>

        // 이벤트1
        $('.btn1').on('click', function(e) {
            alert('눌렀습니다');
            // 매개변수 e(event)의 약자로 사용
            // 클릭함수에 미리정의 된 변수
            console.log(e);
            // 코드실행후 HTML의 href동작 차단시키기
            e.preventDefault();
        });
        
        // 이벤트2
        $('.btn2').on('click', function(e) {
            // this
            // 이벤트가 일어난 대상
            // $('요소명')
            $(this).addClass('on');
            e.preventDefault();
        });

        // 이벤트3
        $('.btn3').on('click', function(e) {

            // attr('속성이름') 속성값 가져오기
            let attr_name = $(this).attr('href');
            console.log(attr_name);
            e.preventDefault();
        });

        //이벤트4
        $('btn4').on('click',function(e){
            let attr_name = $(this).attr('href');
            $('html,body').animate({
                scrollTop : $(attr_name).offset().top
            },500);
            e.preventDefault();
        })


    </script>
 

 

 

LIST

댓글