웹개발 수업/jQuery

[Day +69 / jQuery]기초(8. 이벤트 연결 메소드, 9. Effect, 10. Animate)

Chole Woo 2021. 10. 5. 15:05
211001 금

 

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>8_이벤트 연결 메소드</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

    <style>
        .outer {
            width: 200px;
            height: 200px;
            background: orange;
            padding: 50px;
        }

        .inner {
            width: 100%;
            height: 100%;
            background: red;
        }
    </style>
</head>

<body>



    <h1>이벤트 연결 메소드</h1>
    <h3>
        mouseenter/mouseleave<br>
        mouseover/mouseout
    </h3>

    <h4>mouseenter-mouseleave : 자식 요소 접근 시에는 이벤트 핸들링하지 않음</h4>
    <div class="outer o1">
        <div class="inner"></div>
    </div>
    <p id="output1"></p>


    <h4>mouseover-mouseout : 자식 요소 접근 시에도 이벤트 핸들링 함</h4>
    <div class="outer o2">
        <div class="inner"></div>
    </div>
    <p id="output2"></p>


    <script>
        $(document).ready(function () {
            $(".o1").mouseenter(function () {
                $("#output1").text($("#output1").text() + "ENTER!");
            }).mouseleave(function () {
                $("#output1").text($("#output1").text() + "LEAVE!");
            });
        });

        $(document).ready(function () {
            $(".o2").mouseover(function () {
                $("#output2").text($("#output2").text() + "OVER!");
                // 의미 : 레드와 오렌지 구분이 없다
            }).mouseleave(function () {
                $("#output2").text($("#output2").text() + "OUT!");
                // 의미 : 각각의 요소(레드, 오렌지)를 구분해준다
            });
        });
    </script>


    <hr>

    <h3>키보드 이벤트</h3>
    <pre>
        keydown : 키보드가 눌려질 떄
        keypress : 글자가 입력될 때(기능키 사용 불가)
        keyup : 키보드가 뗴어질 때
    </pre>

    <input type="text" id="inputTest">
    <script>
        $(document).ready(function () {
            $("#inputTest").keydown(function (e) {
                console.log("keydown : " + e.key);
            });
        });

        $(document).ready(function () {
            $("#inputTest").keypress(function (e) {
                console.log("keypress : " + e.key);
            });
        });

        $(document).ready(function () {
            $("#inputTest").keyup(function (e) {
                console.log("keyup : " + e.key);
            });
        });
    </script>


    <hr>

  
    <h3>동적으로 글자 수 세기</h3>
    <div>
        <p><span id="counter">0</span>/150</p>
        <textarea cols="70" rows="5"></textarea>

    </div>
    <script>
        $(document).ready(function(){
            $("textarea").keyup(function(){
                // 현재 요소의 값 길이 알기
                let inputLength = $(this).val().length;
                $("#counter").text(inputLength);

                let remain = 150 - inputLength;

                if(remain >= 0)
                    $("#counter").css("color","black");
                else
                    $("#counter").css("color","red");

            });
        })
    </script>

    <h3>동적으로 아이디 조건 확인</h3>
    <pre>
    - 첫 글자는 반드시 영문 소문자
    - 영문 소문자와 숫자로만 이루어짐
    - 총 6~12자
    </pre>
    <label for="memberId">아이디 : </label>
    <input type="text" name="memberId" id="memberId">
    <span id="idCheck"></span>
    <script>
        // 정규 표현식
        let regExp = /^[a-z][a-z\d]{5,11}$/;

        $("#memberId").keyup(function(){
            if(regExp.test($(this).val())){
                $("#idCheck").css({color:"green", "font-weight":"bold"})
                .text("사용 가능한 아이디 형식입니다");
            }else{
                $("#idCheck").css({color:"red", "font-weight":"bold"})
                .text("사용 불가능한 아이디 형식입니다");

            }
        })
    </script>

    <h3>입력 양식 이벤트</h3>
    <div id="wrap">
        <h3>회원가입</h3>
        <form method="post" action="">
            <table>
                <tr>
                    <td><label>이름</label></td>
                    <td><input type="text" name="name" id="name" required></td>
                    <td><span id="nameresult"></span></td>
                </tr>
                <tr>
                    <td><label>아이디</label></td>
                    <td><input type="text" name="userid" id="userid" required></td>
                    <td><input type="button" value="중복확인"></td>
                </tr>
                <tr>
                    <td><label>비밀번호</label></td>
                    <td><input type="password" name="pwd1" id="pwd1" required></td>
                    <td><span id="pwdresult"></span></td>
                </tr>
                <tr>
                    <td><label>비밀번호확인</label></td>
                    <td><input type="password" name="pwd2" id="pwd2" required></td>
                    <td></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="reset"> &nbsp; <input type="submit"></td>
                    <td></td>
                </tr>
            </table>
        </form>
    </div>
    <script>
        $(function(){
            // 입력 양식 관련 이벤트 감지
            $("#name").focus(function(){
                console.log('FOCUS!');
            }).blur(function(){
                console.log('BLUR!');
            }).change(function(){
                // select, checkbox, radio => 변경 시 바로 이벤트 발생
                // input, textarea => 변경 후 포커스를 잃을 떄 이벤트 발생
                console.log('CHANGE!');
            }).select(function(){
                // 텍스트 영역 블럭 잡힌 경우
                console.log('SELECT!')
            });


            // focusin, focusout : 해당 요소와 자식 요소가 포커스를 가지면 이벤트 발생
            // (focus, blur-버블링 되지 않음)

            $("td").focusin(function(){
                console.log('FOCUSIN!');
            }).focusout(function(){
                console.log('FOCUSOUT!');
            });


            // 이름에는 두 글자 이상의 한글값 작성하기
            $("#name").change(function(){
                let regExp = /^[가-힣]{2,}$/;

                if(regExp.test($(this).val())){
                    $("#nameresult").text("정상 입력").css("color", "green");
                }else{
                    $("#nameresult").text("한글로 두글자 이상 입력").css("color", "red");
                }
            });


            // 비밀번호 확인란 입력시 위의 비밀번호 칸과의 일치 여부 확인
            $("#pwd2").keyup(function(){
                if($("#pwd1").val() != $(this).val()){
                    $("#pwdresult").text("비밀번호 불일치").css("color", "red");
                }else{
                    $("#pwdresult").text("비밀번호 일치").css("color", "green");
                }
            });


            // submit 메소드
            $("form").submit(function(){
                if(!confirm("폼 전송하시겠습니까?"))
                    return false;
            });









        });
    </script>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>9_Effect</title>
    <script src="js/jquery-3.6.0.min.js"></script>

    <style>
        .outer { width : 600px; }

        .menu {
            width: 100%;
            height : 30px;
            background-color: #53a2f9;
            color: #fff;
            border-radius: 5px;
            text-align: center;
            cursor : pointer;
            padding : 5px;
            margin: 5px auto;
        }

        p.content{
            width: 90%;
            height: 200px;
            margin : auto;

            display: none;
            /* 클릭하면 열리게 하고 싶어서 디스플레이 없앰으로 지정 */

        }
    </style>

</head>
<body>
    <h1>시각적 효과</h1>
    <p>
        Effect 메소드 : 페이지에 애니메이션 효과를 만들기 위한 메소드
    </p>
    <pre>
    $('selector').메소드명([speed],[easing],[callback])
    speed : 실행 속도(ms) / 숫자 or slow, fast
    easing : 변경 되는 지점별 속도 / linear, swing
    callback : 메소드 실행 후 실행할 함수
    </pre>

    <h3>show, hide</h3>
    <p>
        문서 객체를 크게하며 보여주거나 작게하며 사라지게 한다
    </p>
    <button id="show">보여주기</button>
    <button id="hide">숨기기</button>
    <img id="river" src="resources/images/river1.PNG"><br>
    <script>
        $(function(){
            $("#show").click(function(){
                $("#river").show(1000);

            });
            $("#hide").click(function(){
                $("#river").hide(1000);
            });
        });
    </script>

    <br><button id="toggle">토글하기</button><br>
    <img id="dog" src="resources/images/sibadog.gif">
    <script>
        $(function(){
            $("#toggle").click(function(){

                // if($("#dog").css("display")=='none'){
                //     $("#dog").show(1000);
                // }else{
                //     $("#dog").hide(1000);
                // }

                $("#dog").toggle(1000);
            })
        })
    </script>


    <h3>slideUp, slideDown</h3>
    <div class="outer">
        <div class="menu">첫 번째 메뉴</div>
        <p class="content">첫 번째 메뉴에 대한 콘텐츠 영역입니다</p>
    </div>

    <div class="outer">
        <div class="menu">두 번째 메뉴</div>
        <p class="content">두 번째 메뉴에 대한 콘텐츠 영역입니다</p>
    </div>

    <div class="outer">
        <div class="menu">세 번째 메뉴</div>
        <p class="content">세 번째 메뉴에 대한 콘텐츠 영역입니다</p>
    </div>

    <div class="outer">
        <div class="menu">네 번째 메뉴</div>
        <p class="content">네 번째 메뉴에 대한 콘텐츠 영역입니다</p>
    </div>

    <div class="outer">
        <div class="menu">다섯 번째 메뉴</div>
        <p class="content">다섯 번째 메뉴에 대한 콘텐츠 영역입니다</p>
    </div>

    <script>
        $(".menu").click(function(){
            if($(this).next("p").css("display") == "none"){
                $("p.content").slideUp();
                $(this).next("p").slideDown();
            }else{
                $(this).next("p").slideUp();
            }
        });
    </script>


    <h3>fade 메소드</h3>
    <pre>
        fadeIn : 점점 진하게 변하면서 보여지는 효과
        fadeOut : 점점 희미하게 변하면서 사라지는 효과
        fadeTo : 설정 값까지 희미해지는 효과(opacity 값으로 투명도 설정)
        fadeToggle : fadeIn과 fadeOut을 동시에 적용
    </pre>

    <button id="fadein">fadeIn</button>
    <button id="fadeout">fadeOut</button><br>
    <img id="diningtable" src="resources/images/diningtable.gif"><br><br>
    <button id="fadeToggle">fadeToggle</button><br>
    <img id="cute" src="resources/images/cute1.gif"><br>
    <img id="flower" src="resources/images/flower1.PNG"><br>
    

    <script>
        $("#fadein").click(function(){
            $("#diningtable").fadeIn(1000);
        });
        $("#fadeout").click(function(){
            $("#diningtable").fadeOut(1000);
        });

        $("#fadeToggle").click(function(){
            $("#cute").fadeToggle(1000, function(){
                alert('토글 완료!');
            });
        });


        $("#flower").hover(function(){
            $("#flower").fadeTo(1000, 0.5);
        }, function(){
            $("#flower").fadeTo(1000, 1);
        });
    </script>


</body>
</html>
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>10_animate</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

    <style>
        .image {
            position: relative;
        }

        .box {
            border: 1px solid black;
            width: 50px;
            height: 50px;
            position: relative;
        }
    </style>
</head>

<body>
    <h1>animate 메소드</h1>

    <pre>
        animate(properties, [duration], [easing], [callback])
        properties : 변경할 CSS 속성을 객체로 전달
        duration : 기본 값은 400, ms | slow | fast
        easing : 속도 옵션 swing | linear
        callback : 애니메이션이 완료되었을 때 호출될 콜백 함수
    </pre>

    <h3>이미지 animate</h3>
    <img src="resources/images/피카츄.gif" width="150px" height="100px" class="image" id="pika">

    <script>
        $("#pika").click(function () {
            $(this).animate({ left: '-158px' }, 'slow');
        });
    </script>


    <h3>상대적 애니메이션</h3>
    <button id="btn">실행확인</button>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>

    <script>
        $("#btn").click(function () {
            $(".box").each(function (index) {
                $(this).css("background", "rgb(255, 200," + (index * 40) + ")");
                $(this).delay(index * 50).animate({ left: '200px' }, 'slow');

            });
        });
    </script>
</body>

</html>
댓글수0