개발새발 블로그

[jQuery] easing종류

카테고리 없음
<!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>easing종류</title>
    <style>
        div  {
            background-color:orange;
            width: 150px; height: 150px;
            position: relative;
        }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js" integrity="sha256-lSjKY0/srUM9BE3dPm+c4fBo1dky2v27Gdjm2uoZaL0=" crossorigin="anonymous"></script>
    <script>
        $(document).ready(function () {
            $('button').click(function () {
                var easing = $('select > option:selected').html();
                // console.log(easing);
                $('div').animate({
                    left: '400'
                }, 2000, easing).animate({
                    left: '0'
                }, 1000, easing);
            });
        });
    </script>
</head>

<body>
    <select>
        <option>linear</option>
        <option>swing</option>
        <option>easeInQuad</option>
        <option>easeOutQuad</option>
        <option>easeInOutQuad</option>
        <option>easeInCubic</option>
        <option>easeOutCubic</option>
        <option>easeInOutCubic</option>
        <option>easeInQuart</option>
        <option>easeOutQuart</option>
        <option>easeInOutQuart</option>
        <option>easeInQuint</option>
        <option>easeOutQuint</option>
        <option>easeInOutQuint</option>
        <option>easeInSine</option>
        <option>easeOutSine</option>
        <option>easeInOutSine</option>
        <option>easeInExpo</option>
        <option>easeOutExpo</option>
        <option>easeInOutExpo</option>
        <option>easeInCirc</option>
        <option>easeOutCirc</option>
        <option>easeInOutCirc</option>
        <option>easeInElastic</option>
        <option>easeOutElastic</option>
        <option>easeInOutElastic</option>
        <option>easeInBack</option>
        <option>easeOutBack</option>
        <option>easeInOutBack</option>
        <option>easeInBounce</option>
        <option>easeOutBounce</option>
        <option>easeInOutBounce</option>
    </select>
    <button>MOVE</button>
    <div></div>
</body>
</html>

[jQuery] ani_nav

카테고리 없음
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>nav</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.3/jquery-ui.min.js"></script>
    <style>
        li{list-style: none; float: left; width: 180px; height: 60px;}
        li a {
            text-decoration: none;
            background-color: rgb(159, 189, 99);
            display: inline-block;
            width: 180px;
            height: 60px;
            color: black;
            text-align: center;
            font: bold 25px Verdana;
            line-height: 60px;
        }
    </style>
    <script>
        $(() => {
            $('li a').hover(function() {
                let overColor = $(this).attr('data-bg');
                $(this).stop().animate({'background-color':overColor, 'color':'white'}, 1000);
            }, function() {
                $(this).stop().animate({'background-color':'#9FBD63', 'color':'black'}, 1000);
            })
        })
    </script>
</head>
<body>
<!-- 
    <ul>
        <li><a href="" data-bg="#EF4018">Home</a></li>
        <li><a href="" data-bg="#00C8C3">About</a></li>
        <li><a href="" data-bg="#AA184D">Portfolio</a></li>
        <li><a href="" data-bg="#05184D">Contact</a></li>
    </ul>
     -->
</body>
</html>

[jQuery] ani_slideDown_slideUp

컴퓨터/jQuery
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>slideDown slideUp</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
    <h1>* slideDown() slideUp()</h1>
<!--
    <p>
        선택된 요소가 점점 위로 말려올라가면서 사라지고 점점 내려오면서 보여지게 하는 메소드
    </p>

    <button id="slideup">SlideUp</button>
    <button id="slidedown">SlideDown</button><br>

    <div id="test1">
        Lorem ipsum, dolor sit amet consectetur adipisicing elit. In ipsum quod numquam, optio voluptate necessitatibus expedita magni dolorum quis inventore sed modi facilis, maxime nesciunt labore cumque provident commodi molestiae!
    </div>

    <script>
        $(() => {
            $('#slideup').click(function() {
                $('#test1').slideUp(2000);
            });
            $('#slidedown').click(function() {
                $('#test1').slideDown(2000);
            });
        })
    </script>

    <hr>
-->
<style>
    div {
        background: beige;
        border: 1px solid yellow;
        border-radius: 10px;
        width: 400px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        cursor: pointer;
    }
    p {
        width: 390px;
        height: 50px;
        border: 1px solid lightgray;
        border-radius: 10px;
        line-height: 50px;
        padding-left: 10px;
        display: none;
    }
</style>

    <h3>질문에 대한 답 보여주기</h3>

    <div>Q. 질문입니다.</div>
    <p>A. 질문에 대한 답변입니다.</p>

    <div>Q. 점심시간은 언제 입니까?</div>
    <p>A. 12시50분 ~ 1시50분까지 입니다.</p>

    <div>Q. 쉬는시간은 언제입니까?</div>
    <p>A. 매시 50분부터 10분간 휴식입니다</p>

    <div>Q. 종료시간은 언제입니까?.</div>
    <p>A. 오후 6시 30분 입니다.</p>

    <div>Q. 본인은 열심히 공부하십니까?</div>
    <p>A. 매일 2시간씩 공부하고 있습니다.</p>

    <script>
        $(() => {
            // 1. div를 클릭하면
            // 2. 선택한요소의 다음 형제( next() )를
            // 3. css(display)==none  보여주고, 그렇지 않으면 숨기기
            $('div').click(function() {
                let $p = $(this).next();
                if($p.css('display')=='none') {
                    $p.slideDown();
                } else {
                    $p.slideUp();
                }
            })
        })
    </script>


</body>
</html>

'컴퓨터 > jQuery' 카테고리의 다른 글

[jQuery] ani_fadeIn_fadeOut  (0) 2024.07.11
[jQuery] ani_hide_show  (0) 2024.07.11
[jQuery] 이벤트  (0) 2024.07.11
[jQuery] 부트스트랩  (0) 2024.07.11
[jQuery] 추가적인 메소드  (0) 2024.07.11

[jQuery] ani_fadeIn_fadeOut

컴퓨터/jQuery
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FadeIn FadeOut</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <style>
        img {
            width: 500px;
            height: 500px;
        }
    </style>
</head>
<body>
    <h1>* fadeIn() fadeOut(), fadeToggle()</h1>
    <p>
        선택된 요소가 점점 투명해지면서 사라지고 점점 선명해지면서 보여지게 하는 메소드
    </p>

    <button id="fadeout">FadeOut</button>
    <button id="fadein">FadeIn</button>
    <button id="fadetoggle">FadeToggle</button><br><br>

    <img id="img1" src="resources/img/img1.jpg">

    <div id="content">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nesciunt culpa accusantium illo fugit dolores non, perspiciatis odit rerum veritatis nisi iste numquam quasi laborum earum temporibus nihil ratione voluptate minima?
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nesciunt culpa accusantium illo fugit dolores non, perspiciatis odit rerum veritatis nisi iste numquam quasi laborum earum temporibus nihil ratione voluptate minima?
    </div>

    <script>
        $(() => {
            $('#fadeout').click(function() {
                $('#img1').fadeOut(2000);
            });
            $('#fadein').click(function() {
                $('#img1').fadeIn(2000);
            });
            $('#fadetoggle').click(function() {
                $('#img1').fadeToggle(2000);
            });
        })
    </script>
</body>
</html>

'컴퓨터 > jQuery' 카테고리의 다른 글

[jQuery] ani_slideDown_slideUp  (0) 2024.07.11
[jQuery] ani_hide_show  (0) 2024.07.11
[jQuery] 이벤트  (0) 2024.07.11
[jQuery] 부트스트랩  (0) 2024.07.11
[jQuery] 추가적인 메소드  (0) 2024.07.11

[jQuery] ani_hide_show

컴퓨터/jQuery
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Effect 메서드</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.3/jquery-ui.min.js"></script>
    <style>
        img {
            width: 500px;
            height: 500px;
        }
    </style>
</head>
<body>
    <h1>시각적인 효과(Effect 메서드)</h1>
    <p>페이지 내에 애니메이션 효과를 주기 위해 사용되는 메서드들</p>

    <h3>* show() hide(), toggle()</h3>
    <p>선택된 요소가 점점 커지면서 보여지고, 점점 작아지면서 사라지게 되는 메소드</p>

    <button id="hide">숨기기</button>
    <button id="show">보여주기</button>
    <button id="toggle">토글</button>

    <br><br>

    <img id="img1" src="resources/img/img1.jpg">

    <div id="content">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nesciunt culpa accusantium illo fugit dolores non, perspiciatis odit rerum veritatis nisi iste numquam quasi laborum earum temporibus nihil ratione voluptate minima?
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nesciunt culpa accusantium illo fugit dolores non, perspiciatis odit rerum veritatis nisi iste numquam quasi laborum earum temporibus nihil ratione voluptate minima?
    </div>

    <script>
        $(() => {
            $('#hide').click(function() {
                $('#img1').hide(2000, "easeInOutQuint");
            });
            $('#show').click(function() {
                $('#img1').show(2000);
            });
            $('#toggle').click(function() {
                $('#img1').toggle(2000, 'easeOutBounce');
            });
        })
    </script>
</body>
</html>

'컴퓨터 > jQuery' 카테고리의 다른 글

[jQuery] ani_slideDown_slideUp  (0) 2024.07.11
[jQuery] ani_fadeIn_fadeOut  (0) 2024.07.11
[jQuery] 이벤트  (0) 2024.07.11
[jQuery] 부트스트랩  (0) 2024.07.11
[jQuery] 추가적인 메소드  (0) 2024.07.11

[jQuery] 이벤트

컴퓨터/jQuery
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>이벤트</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
    <h1>이벤트 핸들러(이벤트 발생시 실행될 function) 연결 방법</h1>

    <h3>방법1. 이벤트 메서드를 이용한 연결</h3>
    <pre>
        $('선택자').이벤트메서드(function() {
            해당요소에 해당 이벤트가 발생되면 실행할 내용;
        })
    </pre>

    <h4 id="test1">클릭해보세요</h4>

    <script>
        $(() => {
            $('#test1').click(function() {
                $(this).html('클릭되었습니다!!!');
            });
            $('#test1').dblclick(function() {
                $(this).css('color','red');
            });
        })
    </script>

    <br>

    <h3>방법2. on 메서드를 이용한 연결</h3>
    <pre>
        $('선택자').on('이벤트명', function() {
            해당요소에 이벤트가 발생되면 실행할 내용;
        });
    </pre>

    <h4 id="test2">마우스 클릭 및 올려보세요</h4>

    <script>
        $(()=> {
            /*
            $('#test2').on('mouseenter', function() {

            });
            $('#test2').on('mouseout', function() {

            });
            $('#test2').on('click', function() {

            });
            */

            $('#test2').on({mouseenter:function(){
                $(this).css('backgroundColor','yellowgreen')
                       .text('마우스가 올라옴'); 
            }, mouseout:function(){
                $(this).css('backgroundColor','yellow')
                       .text('마우스가 빠져나감');
            }, click:function(){
                // off('이벤트명') : 이벤트 제거
                $(this).off('mouseenter')
                       .off('mouseout')
                       .css('color','orange')
                       .text('클릭됨');
            }});
        })
    </script>

    <br>

    <h3>방법3. on 메서드를 이용한 하위요소에 이벤트 걸기</h3>
    <pre>
        $('상위요소선택자').on('이벤트명', '하위요소선택자(이벤트를 걸고자하는 요소)',function() {
            해당요소에 이벤트가 발생되면 실행할 내용;
        });
    </pre>

    <div id="test3">
        <h4>h4를 클릭해보세요</h4>
        <h5>h4를 클릭해보세요</h5>
    </div>
    <h5>div 바깥쪽 h5</h5>

    <script>
        $(() => {
            $('#test3').on('click', 'h4, h5', function() {
                $(this).html('안녕');
            });
            $(document).on('click','h5',function() {
                $(this).css('color', 'red');
            });
        })
    </script>

    <hr>

    <h3>** 동적으로 만들어진 요소에도 동일한 이벤트를 적용시키고자 한다면 반드시 방법3으로 해야됨</h3>
    <!-- 동적으로 만들어진 요소 : 처음에 문서 로딩시에는 없다가 나중에 새롭게 만들어진 요소 -->

    <div id="test4" style="border:1px solid red">
        <h6>기존에 존재하는 h6</h6>
    </div>

    <script>
        $(() => {
            // 방법1
            /*
            $('#test4>h6').click(function() {
                $('#test4').append('<h6>클릭으로 인해 동적으로 만들어진 h6</h6>');
            });
            */

            // 방법2
            /*
            $('#test4>h6').on('click', (function() {
                $('#test4').append('<h6>클릭으로 인해 동적으로 만들어진 h6</h6>');
            }));
            */

            // 방법3 => 동적으로 만들어진 요소에 이벤트 적용됨
            $('#test4').on('click', 'h6', function() {
                $('#test4').append('<h6>클릭으로 인해 동적으로 만들어진 h6</h6>');
            });
        })
    </script>

    <hr>

    <h3>* 일회성 이벤트(one 메서드)</h3>

    <h6 id="test5">딱 한번만 클릭시 실행</h6>

    <script>
        $(() => {
            $('#test5').one('click', function() {
                alert('처음이자 마지막으로 이벤트 실행');
            });
        })
    </script>

    <hr>

    <h3>* 키보드 관련 이벤트</h3>
    <p>
        - keydown | keypress : 키가 눌려질때 발생하는 이벤트<br>
          > keydown : 키보드의 모든 키가 눌려질 때 발생됨<br>
          > keypress : 키보드의 펑션키, 기능키, 한글 제외한 나머지 키가 눌려질 때 발생됨<br>
        - keyup : 키를 눌렀다 떼었을 때 발생되는 이벤트
    </p>

    <input id="test6">

    <script>
        $(() => {
            $('#test6').keyup(function() {
                // console.log('키를 눌렀음');
                console.log($(this).val());
                console.log('문자열 길이 : ', $(this).val().length);
            })
        })
    </script>

    <h3>* 동적으로 글자수 세기</h3>

    최소 10글자 이상 최대 150자 이내로 작성하시오<br>
    <textarea style="resize: none;" cols='30' rows="10" id="content"></textarea><br>
    <span id="count">0</span> / 150

    <script>
        $(() => {
            $('#content').keyup(function() {
                $('#count').text($(this).val().length);
            })
        })
    </script>
</body>
</html>

'컴퓨터 > jQuery' 카테고리의 다른 글

[jQuery] ani_fadeIn_fadeOut  (0) 2024.07.11
[jQuery] ani_hide_show  (0) 2024.07.11
[jQuery] 부트스트랩  (0) 2024.07.11
[jQuery] 추가적인 메소드  (0) 2024.07.11
[jQuery] 요소 생성 및 제거 메소드  (0) 2024.07.10

[jQuery] 부트스트랩

컴퓨터/jQuery
<!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">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <title>게시판 리스트</title>
    <style>
        body {padding: 0 80px;}
        table {
            border: 1px solid;
            border-collapse: collapse;
        }
        tbody>tr:hover {
            cursor:pointer;
        }
    </style>
</head>
<body>
    <br><br>
    <h2 align="center">게시판 리스트</h2><br>
    <table border="1" class="table table-hover">
        <thead>
            <tr>
                <th>글번호</th>
                <th>제목</th>
                <th>작성자</th>
                <th>조회수</th>
                <th>작성일</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>3</td>
                <td>세번째 글 제목</td>
                <td>user01</td>
                <td>23</td>
                <td>2023-03-31</td>
            </tr>
            <tr>
                <td>2</td>
                <td>두번째 글 제목</td>
                <td>user02</td>
                <td>15</td>
                <td>2023-03-13</td>
            </tr>
            <tr>
                <td>1</td>
                <td>첫번째 글 제목</td>
                <td>admin</td>
                <td>75</td>
                <td>2023-03-12</td>
            </tr>
        </tbody>
    </table>

    <br><br>
    
    선택된 게시글 정보 :
    <span id="s0">글번호</span> /
    <span id="s1">제목</span> /
    <span id="s2">작성자</span> /
    <span id="s3">조회수</span> /
    <span id="s4">작성일</span>

    <script>
        $(() => {
            $('tbody>tr').click(function() {
                // console.log($(this).children().eq(0).text());
                // console.log($(this).children().eq(1).text());

                $(this).children().each(function(index, el) {
                    //console.log($(el).text());
                    $('#s'+index).text($(el).text());
                });
            });
        })
    </script>

    <br><br>
    
    <button type="button" class="btn btn-success btn-lg">회원가입</button>&emsp;
    <button type="button" class="btn btn-secondary btn-sm">회원탈퇴</button><br><br>
    
    <button type="button" class="btn btn-outline-success">회원가입</button>&emsp;
    <button type="button" class="btn btn-outline-secondary">회원탈퇴</button>

    <br><br>
    <form action="">
        <div class="mb-3">
            <label for="uId" class="form-label">ID : </label>
            <input type="text" class="form-control" id="uId" placeholder="name@example.com">
        </div>
        <div class="mb-3">
            <label for="pwd" class="form-label">Password : </label>
            <input type="password" class="form-control" id="pwd" placeholder="특수문자1개,영문자1개,숫자1개 반드시 포함">
        </div>
        <button type="submit" class="btn btn-outline-danger">로그인</button>
    </form>

    <br><br>

    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@mdo">로그인</button>

    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="exampleModalLabel">로그인 하기</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form>
                        <div class="mb-3">
                            <label for="id" class="col-form-label">ID :</label>
                            <input type="text" class="form-control" id="id">
                        </div>
                        <div class="mb-3">
                            <label for="pw" class="col-form-label">PW :</label>
                            <input type="password" class="form-control" id="pwd">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">로그인</button>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

'컴퓨터 > jQuery' 카테고리의 다른 글

[jQuery] ani_hide_show  (0) 2024.07.11
[jQuery] 이벤트  (0) 2024.07.11
[jQuery] 추가적인 메소드  (0) 2024.07.11
[jQuery] 요소 생성 및 제거 메소드  (0) 2024.07.10
[jQuery] content영역 관련 메소드  (0) 2024.07.10

[jQuery] 추가적인 메소드

컴퓨터/jQuery
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>추가적인 메소드</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <style>
        .highlight-0{background-color: red;}
        .highlight-1{background-color: orange;}
        .highlight-2{background-color: yellow;}
        .highlight-3{background-color: green;}
        .highlight-4{background-color: blue;}
    </style>
</head>
<body>
    <h1>추가적인 메서드</h1>
    <h3>* each메서드</h3>
    <p>
        배열의 모든 인덱스에 순차적으로 접근할 때 사용<br>
        객체가 가지고 있는 모든 속성에 순차적으로 접근하고자 할 때<br>
        for in문과 유사하게 수행되는 메서드
    </p>

    <pre>
        1) $.each(객체|배열, function([매개변수1, 매개변수2]) {
                순차적으로 접근할 때마다 실행할 내용;
           });
        2) 객체 배열.each(function([매개변수1, 매개변수2]) {
                순차적으로 접근할 때마다 실행할 내용;
            })

           만약 객체를 제시했다면
           첫번째 매개변수에는 순차적으로 접근할 때 마다의 객체의 속성명(키)가 담김
           두번째 매개변수에는 해당 속성값(value)이 담김
           
           만약 배열을 제시했다면
           첫번째 매개변수에는 순차적으로 접근할 때 마다 인덱스가 담김
           두번째 매개변수에는 해당 인덱스값이 담김
    </pre>

    <script>
        $(() => {
            const arr = ['강', '남', '하', '동']

            // 1) for in 사용
            for(let index in arr) {
                console.log(`인덱스 : ${index}, 값 : ${arr[index]}`);
            }

            console.log('----------------------------');

            // 2) each메소드 방법 1
            $.each(arr, function(index, value) {
                console.log(`인덱스 : ${index}, 값 : ${value}`);
            })

            console.log('----------------------------');

            // 3) each메소드 방법 2
            $(arr).each(function(index, value) {
                console.log(`인덱스 : ${index}, 값 : ${value}`);
            })

            console.log('=============================');

            const student = {
                name:'홍길동',
                age:20,
                address:'서울'
            }

            // 1) for in 사용
            for(let key in student) {
                console.log(`속성명 : ${key}, 속성값 : ${student[key]}`);
            }

            // 2) each 사용
            $.each(student, function(key, value) {
                console.log(`속성명 : ${key}, 속성값 : ${value}`);
            })

            //------------------------------------------------------------
            $('#btn').click(function() {
                const students = [{name:'홍길도',age:20,addr:'서울'},
                                  {name:'방인중',age:25,addr:'경기'},
                                  {name:'우재남',age:23,addr:'인천'}];
                
                let result = '';
                $(students).each(function(index, obj) {
                    result += `<tr>
                                    <td>${obj.name}</td>
                                    <td>${obj.age}</td>
                                    <td>${obj.addr}</td>
                               </tr>`;
                });

                console.log(result);
                $('#area1 tbody').html(result);
            })
        })
    </script>

    <button id="btn">학생조회</button>

    <table id="area1" border="1">
        <thead>
            <tr>
                <th>이름</th>
                <th>나이</th>
                <th>주소</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>

    <br><br>

    <div id="area2">
        <h1>item-1</h1>
        <h1>item-2</h1>
        <h1>item-3</h1>
        <h1>item-4</h1>
        <h1>item-5</h1>
    </div>

    <script>
        $(() => {
            $('#area2').children().each(function(index/*, el*/) {
                // console.log(el);
                // el.addClass('highlight-' + index); // 안됨

                // el : javascript방식으로 선택된 요소 객체가 들어있음(직접 속성에 접근하여 값 변경)
                // el.className = 'highlight-' + index;

                // jQuery
                // $(el).addClass('highlight-' + index);

                $(this).addClass('highlight-' + index);
            })
        })
    </script>

    <hr>

    <h3>* is메서드</h3>
    <p>
        $('선택자').is('선택자')<br>
        선택된 요소가 내가 전달한 값과 일치하는지 판단하여 그에 해당하는 논리값 반환
    </p>

    <h3 class="test">test1</h3>
    <h3>test2</h3>
    <h3 class="test">test3</h3>
    <h3 class="test">test4</h3>
    <h3>test5</h3>
    <h3 class="test">test6</h3>

    <script>
        $(() => {
            $('h3').each(function() {
                if($(this).is('.test')) {
                    $(this).css('backgroundColor', 'yellowgreen');
                }
            })
        })
    </script>
</body>
</html>

'컴퓨터 > jQuery' 카테고리의 다른 글

[jQuery] 이벤트  (0) 2024.07.11
[jQuery] 부트스트랩  (0) 2024.07.11
[jQuery] 요소 생성 및 제거 메소드  (0) 2024.07.10
[jQuery] content영역 관련 메소드  (0) 2024.07.10
[jQuery] 요소 탐색(순회)메소드 동위  (0) 2024.07.10

[jQuery] 요소 생성 및 제거 메소드

컴퓨터/jQuery
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>요소 생성 및 제거 메소드</title>
    <script src="https://code.jquery.com/jquery-3.7.1.slim.js"></script>
    <style>
        .added {color: aquamarine;}
        .item {
            background-color: yellowgreen;
            width: 100px;
            height: 100px;
            text-align: center;
            line-height: 100px;
            margin: 5px;
        }
        .item span {
            font-size: 25px;
            color: white;
            font-weight: bold;
        }
        .purple {background-color: purple;}
    </style>
</head>
<body>
    <h1>요소 생성 및 제거</h1>
    <h3>* 동적으로 요소 생성</h3>

    <button id="btn">요소 생성</button>
    <div id="area1"></div>

    <script>
        $(() => {
            $('#btn').click(function() {
                // 1. 문자열 생성
                let el1 = '<p>Create Element By Text</p>';

                // 2. DOM메소드로 만드는 방법(createElement, createTextNode)
                let el2 = document.createElement('p');      // <p></p>
                let text = document.createTextNode('Create Element By Text');
                el2.appendChild(text);

                // 3. jQuery로 만드는 방법
                // let el3 = $('<p></p>').text('Create Element By Text');
                // console.log(el3);

                let el3 = $('<p>Create Element By Text</p>');
                console.log(el3);

                $('#area1').append(el1, el2, el3);
            });
        })
    </script>

    <hr>

    <h3>* 삽입 관련 메서드 part1</h3>
    <p>
        선택된 요소를 기준으로 새로운 요소들을 추가시켜주는 메서드<br><br>

        $(A).append(B) : A요소 내에 뒷부분에 B를 추가(자손/하위)<br>
        $(A).prepend(B) : A요소 내에 앞부분에 B를 추가(자손/하위)<br><br>

        $(A).after(B) : A요소 뒷부분에 B를 추가(동위)<br>
        $(A).before(B) : A요소 앞부분에 B를 추가(동위)<br><br>
    </p>

    <h3>* 삽입 관련 메서드 part2</h3>
    <p>
        선택된 요소를 기준으로 새로운 요소들을 추가시켜주는 메서드<br><br>

        $(B).appendTo(A) : A요소 내에 뒷부분에 B를 추가(자손/하위)<br>
        $(B).prependTo(A) : A요소 내에 앞부분에 B를 추가(자손/하위)<br><br>

        $(B).insertAfter(A) : A요소 뒷부분에 B를 추가(동위)<br>
        $(B).insertBefore(A) : A요소 앞부분에 B를 추가(동위)<br><br>
    </p>

    <h1 id="test1"><span>A</span></h1>
    <h1 id="test2"><span>A</span></h1>
    <h1 id="test3"><span>A</span></h1>
    <h1 id="test4"><span>A</span></h1>

    <script>
        $(() => {
            // part1
            $('#test1').append('<span class="added">B</span>');
            $('#test2').prepend('<span class="added">B</span>');

            $('#test3').before('<span class="added">B</span>');
            $('#test4').after('<span class="added">B</span>');

            // part2
            /*
            $('<span class="added">B</span>').appendTo('#test1');
            $('<span class="added">B</span>').prependTo('#test2');

            $('<span class="added">B</span>').insertAfter('#test3');
            $('<span class="added">B</span>').insertBefore('#test4');
            */
        })
    </script>

    <hr>

    <h3>* 요소 객체 복제 메서드</h3>
    <p>
        $('선택자').clone([true|false]) : 선택된 요소를 복제하여 반환해주는 메서드<br>
        - true|false : 복제할 요소에 걸려있는 이벤트까지도 복제할 것인지를 지정(기본값 false)
    </p>

    <div id="clone-test">
        <!-- 복제할 요소-->
         <div id="item1" class="item">
            <span>안녕</span>
         </div>
    </div>

    <button id="clone">복제하기</button>
    <div id="clone-result"></div>

    <script>
        $(() => {
            // 이벤트 넣기
            $('.item').hover(function() {
                $(this).addClass('purple');
            }, function() {
                $(this).removeClass('purple');
            })

            // 버튼을 누르면 복제
            $('#clone').click(function() {
                // const copy = $('#item1').clone();    이벤트복제 x(기본값)
                const copy = $('#item1').clone(true);   // 이벤트까지 복제
                $('#clone-result').append(copy);

                // $('#clone-result').append($('#item1').clone(true));

                // $('#item1').clone(true).appendTo('#clone-result');
            });
        })
    </script>

    <hr>

    <h3>* 요소를 제거 및 잘라내기 메소드</h3>
    <p>
        $('선택자').empty() : 선택된 요소의 하위 요소들을 제거해주는 메서드<br><br>

        변수 = $('선택자').remove|detach() : 선택된 요소를 제거한 후 해당 요소를 반환해주는 메서드<br>
         > remove() : 잘라내기할 때 잘라낸 요소의 이벤트를 가져오지 않음<br>
         > detach() : 잘라내기할 때 잘라낸 요소의 이벤트를 가져옴<br>
    </p>

    <div id="remove-test">
        <!-- 제거할 요소 -->
         <div id="item2" class="item">
            <span>안녕</span>
         </div>
    </div>

    <button id="empty">제거</button>
    <button id="remove">잘라내기(remove)</button>
    <button id="detach">잘라내기(detach)</button>

    <div id="remove-result"></div>

    <script>
        $(() => {
            $('#empty').click(function() {
                // $('#item2').empty();        // 'item2'요소의 하위요소를 삭제 <span>안녕</span>
                $('#remove-test').empty();     // div 통째로 삭제
            });
            
            $('#remove').click(function() {
                const el = $('#item2').remove();
                $('#remove-result').append(el);
            });

            $('#detach').click(function() {
                const el = $('#item2').detach();
                $('#remove-result').append(el);
            });
        })
        /*
        요소.css('스타일속성','값') : 변경
        요소.css('스타일속성') : 반환

        요소.val('텍스트') : 속성 value의 값 변경
        요소.val() : 속성 value의 값 반환

        요소.html|text('텍스트') : 변경
        요소.html|text() : 반환

        요소.attr('그외속성명', '값') : 변경
        요소.attr('그외속성명') : 반환

        요소.이벤트(function() {})

        요소.addClass('클래스명') : 클래스 삽입
        요소.removeClass('클래스명') : 클래스 제거
        */
    </script>
</body>
</html>

[jQuery] content영역 관련 메소드

컴퓨터/jQuery
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>content영역 관련 메소드</title>
    <script src="https://code.jquery.com/jquery-3.7.1.slim.js"></script>
</head>
<body>
    <h1>Content (innerHTML, innerText) 관련 메소드</h1>
    <h3>* html(['문구']) 메소드 : innerHTML 속성과 관련된 메소드</h3>

    <p>
        선택된 요소의 content영역의 값을 리턴해주거나 또는 변경해주는 메서드<br>
        > $('선택자').html() : 선택된 요소의 content영역 값을 반환해줌(html태그 포함)<br>
        > $('선택자').html('문구') : 선택된 요소의 content영역 값을 해당 문구로 변경해 줌(html태그가 존재하면 태그로써 해석함)
    </p>

    <h1 id="test1">
        <a>네이버로</a>
    </h1>

    <h1 id="test2">
        
    </h1>

    <script>
        $(() => {
            // const tmp = document.getElementById('test1');
            const tmp = $('#test1').html();
            console.log(tmp);

            $('#test2').html(tmp);
            $('#test2').children().attr('href', 'https://naver.com');
        })
    </script>

    <h3>* text(['문구']) 메소드 : innerText 속성과 관련된 메소드</h3>
    <p>
        선택된 요소의 content영역의 값을 리턴해주거나 또는 변경해주는 메서드<br>
        > $('선택자').text() : 선택된 요소의 content 영역의 값을 반환(html태그는 포함x, 오로지 text만)<br>
        > $('선택자').text('문구') : 선택된 요소의 content 영역의 값을 제시한 문구로 변경(html태그가 존재할 경우 태그해석x)
    </p>

    <h1 id="test3">
        <a>구글로</a>
    </h1>
    
    <h1 id="test4">

    </h1>

    <script>
        $(() => {
            // const tmp = document.getElementById('test3').innerText;
            const tmp = $('#test3').text();
            console.log(tmp);

            $('#test4').text('<a>' + tmp + '</a>');
        })
    </script>

    <hr>

    <div class="test">테스트</div>
    <div class="test">테스트</div>
    <div class="test">테스트</div>

    <script>
        $(() => {
            // class가 test인 요소객체의 글자를 <h1>변경됨</h1>
            $('.test').html('<h1>변경됨</h1>');

            // 선택된 요소들을 순차적으로 접근할 때마다 해당 function이 실행 됨
            // 이때 함수 실행시 리턴된 값으로 문구 변경(콜백함수)
            let count = 0;
            $('.test').html(function() {
                return `<h1>다시 변경 ${++count}</h1>`;
            });

            $('.test').html(function(index, html) {
                return `<h1>인덱스 : ${index}, content내용 : ${html}</h1>`;
            });
            // text()도 마찬가지임
        })
    </script>
</body>
</html>