JavaScript

부트캠프40일(jQuery 요소관련, 이벤트핸들러)

동곤일상 2025. 3. 31. 16:15
반응형

1) jQuery 탐색(sideways)

2) 요소생성

3)삽입관련메서드

4)복제관련 메서드

5) 요소제거 및 잘라내기

6)each

7) is메서드

8) 이벤트핸들러

8-1)click , dbclick

8-2) on메서드이용

8-3)일회성이벤트 one

8-4)간단예제

8-5)기본이벤트 무시

8-6)이벤트발생요소 검색

8-7)시각적효과

 


1) jQuery 탐색(sideways)

 

$("선택자").silbling() 

선택자의요소와 같은레벨의 다른요소 모두선택

 

$("선택자" ).silbling("선택자2")

선택자의요소와 같은레벨의 다른요소 중

선택자2의요소만 선택

 

next()

해당태그 다음의 태그

 

nextAll()

해당태그 다음의 태그 모두

 

$("선택자").nextUntil("선택자2")

선택자이후~선택자2까지 선택

 

prev() : 해당태그 바로 전의 태그

 

prevAll() : 태그의 앞쪽(전)요소 모두

 

$("선택자").prevUntil("선택자2")

선택자이전~선택자2까지 선택

(선택자2는 포함X)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .wrap , .wrap *{ /*wrap과 wrap의 모든하위태그 적용*/
            border: 1px solid lightgray;
            display: block;
            padding: 5px;
            margin: 20px; /*외부와의 간격 15px*/
            color: gray;
        }
    </style>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
    <h3>sideways(동위)
메서드기준이요소와같은레벨에있는 다른요소들을 선택할수있는 메서드</h3>
        <div class="wrap">
            <p>p</p>
            <span>span</span>
            <h2>h2</h2>
            <h3>h3</h3>
            <p>p</p>
        </div>
        <script>
            $(function(){
                const style1 = {color:"red",border:"2px solid red"};
                const style2 = {color:"blue",border:"2px solid blue"};
                const style3 = {color:"yellow",border:"2px solid yellow"};
                const style4 = {backgroundColor:"aqua",color:"red"};
                //$("선택자").siblings()
                //선택된요소와 같은레벨(같은블럭)의 다른요소 모두 선택
                $("h2").siblings().css(style1);

                //$("선택자").siblings("선택자2")
                //선택된요소와 같은레벨의 다른요소 중 선택자2요소
                $("h2").siblings("p").css(style2);

                /*
                next() | prev(): 해당태그의 바로 다음 | 앞 요소 1개
                nextAll() | prevAll(): 해당태그 다음 | 앞 요소 전부
                */
                $("h2").next().css(style3);
                $("h2").nextAll().css(style4);

                //nextUntil("p") : 선택이후의 p태그 앞 까지
                $("h2").nextUntil("p").css("font-size" , "3em");
                $("h2").prev().css("backgroundColor" , "pink");
                $("h2").prevAll().css(style4);
                //$("선택자").prevUntil("p") 선택자 이전의 p태그 앞 까지
                $("h2").prevUntil("p").css("border-style","dotted");

            })

        </script>
    
</body>
</html>

 


2) 요소생성 

$("태그").text("..")

태그를 생성하고 text를 붙인다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<h1>요소의 생성</h1>
<h3>동적으로 요소 생성</h3>
<button id="btn">요소생성</button>
<div id="area1"></div>
  
</body>
</html>
<script>
    $(function(){
        $("#btn").click(function(){
            //1.문자열로생성
            let el1 = "<p> Create Element By String </p>"

            //2. DOM 함수 이용createElement, createTextNode
            //p태그 생성
            let el2 = document.createElement("p");
            //텍스트노드를 만든다
            let text = document.createTextNode("Create Element By DOM");
            el2.appendChild(text);//p태그에 text를 넣는다
            //3 jQuery로 요소 생성
            let el3 = $("<p></p>").text("Create Elemet By jQuery")
            $("#area1").append(el1,el2,el3);//el1,2,3를 area1에 붙인다.
            console.log(el1)
            console.log(el2)
            console.log(el3)
        })
    })
</script>


3)삽입관련메서드

$(A).append(B) : A요소 내에 뒷부분에B추가(자손/하위)

$(A).prepend(B) : A요소 내에 앞부분에B추가(자손/하위)

 

$(A).after(B) : A요소 뒷부분에 B추가(자손/하위)

$(A).before(B) : A요소 앞부분에 B추가

 

$(B).appenTo(A) : B를 A요소 내의 뒷부분에 하위요소

$(B).prependTo(A) : B를 A요소 내의 앞부분에 하위요소

$(B).insertAfter(A) : B를 A요소 뒤에 추가(동위)

$(B).insertBefore(A) : B를 A요소 앞에 추가(동위)

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<h3>삽입관련메서드</h3>
<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>
   $(function(){
      
        $("#test1").append("<span>B</span>") 
        $("#test2").prepend("<span>B</span>")              
        $("#test4").after("<span>B</span>")        
        $("#test3").before("<span>B</span>")
               
        $("<span>C</span>").appendTo("#test1")        
        $("<span>C</span>").prependTo("#test2")
        
        $("<span>C</span>").insertAfter("#test3")
        
        $("<span>C</span>").insertBefore("#test4")
    })
</script>   
</body>
</html>

 


4) 복제관련메서드 clone()

clone(true) : 요소와 이벤트 모두 복제

기본값 : false(요소만복제)

<style>
  .purple{
            background:purple;
        }
 </style>
 <body>
<h3>요소복제메서드</h3>
<div id="clone-test">
    <div id="item1" class="item"><span>안녕</span></div>
</div>
<button id="clone">복제</button>
<div id="clone-result"></div>

<script>
    $(function(){
        $(".item").hover(function(){
            $(this).addClass("purple");//마우스를 가져다댔을 때
        },function(){
            $(this).removeClass("purple")//범위를 벗어날 때
        })
        $("#clone").click(function(){
            // $("#clone-result").append($("#item1"));//복제가 아닌 이동
            //clone() : 기본값=false
            // const copyEl = $("#item1").clone();//요소복제:O , 이벤트복제X
            // $("#clone-result").append(copyEl);

            //clone(true) : 요소와 이벤트 모두 복제
            // $("#clone-result").append($("#item1").clone(true))
            $("#item1").clone(true).appendTo($("#clone-result"));
        })
})
</script>
</body>

 

 

 


5)요소제거 및 잘라내기

 

empty () : 제거

remove() : 제거 후 요소 리턴 (이벤트X)

detach() : 제거 후 요소리턴 + 이벤트 리턴

<h1>요소제거</h1>
<h3>요소객체 제거 및 잘라내기 메서드</h3>
<div id="remove-test">
    <div id="item2" class="item"><span>안녕</span></div>
    <h1>안녕하세요</h1>
</div>
<button id="empty">비우기</button>
<button id="remove">제거</button>
<button id="detach">잘라내기</button>
<div id="remove-result"></div>
<script>
    $(function(){
        $("#empty").click(function(){
            $("#remove-test").empty();
            //remove-test태그 내의 모든 객체 제거
        })
        $("#remove").click(function(){
            const removeEl = $("#item2").remove();
            //제거요소 리턴(이벤트는 리턴X)
            $("#remove-result").append(removeEl);
        })

        $("#detach").click(function(){
            //detach() : 제거된요소리턴+이벤트리턴
            const detachEl = $("#item2").detach();
            $("#remove-result").append(detachEl);
        })
    })
</script>

 

 


6) each

   배열의 모든 인덱스 순차적으로 접근할 때 사용
    for in , forEach 구문과 비슷
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
    $(function(){
        const arr = ["동","서","남","북"];
        //1 for in
        //모든요소를 순회
        for(let i in arr){
            console.log(i , typeof i);//string
            console.log(arr[i])
        }
        console.log("----------------")

        //2 forEach
        //인덱스없이 루프
        arr.forEach((item)=>console.log(item))
        console.log("----------------")

        //3 each
        //fuction을 이용해 index,value값전달
        $.each(arr,function(index,value){
            console.log(index,typeof(index))//Number
            console.log(value)
        })
        
        //each2 (배열만 사용가능한방식)
        console.log("----------------")
        $(arr).each(function(index,value){
            console.log(index,typeof(index))
            console.log(value)
        })
        /*순수 자바스크립트 방식의 배열객체
        arr을 jQuery객체 $(arr)로 변경해야  each메서드호출가능
        */
        console.log("----------------")
       const student  = {name:"홍길동",age:20,address:"서울"};
       for(let key in student){
        console.log(key , typeof(key));
        console.log(student[key])
       }

       console.log("----------------")

       //each 1 
       $.each(student,function(key,value){
        console.log(key , typeof key)
        console.log(student[key])
       })
       //each 2 ==> 배열만 가능
       /*
       $(student).each(function(key,value){
        console.log(key , typeof key)
        console.log(student[key])
    })*/

    })
</script>


each 관련 예제

<button id="btn">학생조회</button><br><br>
<table id="result1" border="1">
    <thead><tr><th>이름</th><th>나이</th><th>주소</th><th></th></tr>
    </thead>
    <tbody>
        <!--버튼 클릭시 조회된 학생정보 출력-->
        <tr><td colspan="4" style="text-align: center;">현재 학생정보X</td></tr>
    </tbody>
</table>
<script>
    $(function(){
        $("#btn").click(function(){
            const student = [{name:"홍길동" , age:20 , address:"서울", phone:"010-1111-2222"},
            {name:"김삿" , age:30 , address:"울산", phone:"010-6671-2552"},
            {name:"이범" , age:40 , address:"서산", phone:"010-8661-2112"},]
            //학생수만큼 tr요소 생성해 student정보를 tbody내에 출력하기
            
            let result = "";
            $(student).each(function(key,st){
                result += `<tr><td>${st.name}</td><td>${st.age}</td>
                    <td>${st.address}</td><td>${st.phone}</td></tr>`;
            })
            $("#result1>tbody").html(result)
        })
    })
</script>


순수자바스크립트 요소객체와

jQuery방식의 요소객체 (addClass)

   <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>
        $(function(){ 
            /*
            $("#area2").children().each(function(index , el){
                console.log(index)
                console.log(el)//순수 자바스크립트요소객체
                console.log($(el))//jQuery방식의 요소객체
            })*/
           $.each($("#area2").children(),function(index){
            //this :  순차적으로 접근되는 요소객체(자바스크립트객체)
            //$(this) : jQuery방식의 요소객체 (addClass사용을위한)
            
            // this.className = "highlight-"+index; 같은 뜻
            //$(this).className = 사용불가!!!!!!!
            $(this).addClass("highlight-"+index);
            // this.addClass() 사용불가!!!!!
           })
        })
    </script>


7) is메서드

 $("선택자1").is("선택자2")

   선택자1 와 선택자2의  일치 여부 리턴(논리값 반환)

 <h3>is 메서드</h3>
    <p>
        $("선택자1").is("선택자2")<br>
        선택자1 와 선택자2의  일치 여부 리턴(논리값 반환)
    </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>
        $(function(){
            $("h3").each(function(){
                //$(this) : h3태그중 현재순회중인 h3요소 1개
                if($(this).is(".test")){ //this태그의 class가 test라면
                    
                    $(this).css("backgroundColor","orange")
                    $(this).css("width",200)
                    
                }
            })
            //h3태그 중 class='test'
            $("h3.test").css({backgroundColor:"red"}) //위에와같은뜻이긴 함
        })
    </script>

 


8) 이벤트핸들러

특정 이벤트(클릭, 입력, 마우스 이동 등)가 발생했을 때 실행되는 함수

 


 

8-1)click , dbclick

<body>
    <h1>이벤트핸들러 연결 방법</h1>
    <h3>이벤트메서드 이용</h3>
    <h4 id="test1">클릭</h4>
    <script>
        $(function(){
            $("#test1").click(function(){
                //this : 이벤트소스(target)
                $(this).text("클릭되었어요");
            })
            $("#test1").dblclick(function(){//doubleClick
                $(this).css({color:"red"});
            })

            $("#test1").click(function(){
                $(this).css({backgroundColor:"yellow"});
            })

        })
    </script>
    
</body>

 


8-2) on메서드 이용

(1) on()
 

- 하나의 요소에 여러개의 이벤트 등록이 가능.  

 - 동적 생성 요소에 이벤트 등록 가능  

 - 이벤트 등록 방식

정적/동적 요소에 등록

$(이벤트 대상).on("이벤트 타입",이벤트 핸들러)

 

  동적 요소에 등록

 $(부모).on("이벤트 타입",이벤트 대상요소, 이벤트 핸들러)


 (2) one()                  

  - 일회성 이벤트로 등록.
 - 이벤트 등록 방식
$(이벤트대상요소).one("이벤트 타입",이벤트 핸들러)


(3) off()
 - 등록된 이벤트 제거.
 - 이벤트 제거 방식
 $(이벤트 대상).off("이벤트 타입")

 <h3>on메서드이용</h3>
    <h4 id="test2">마우스클릭 및 올려보세요</h4>
     <script>
        //on 메서드 : 하나의요소에 1개이상의 이벤트 등록가능
        //이벤트:function(){...}과 같은형태로 사용가능
        $(function(){
            $("#test2").on({mouseover:function(){ //mouseover이벤트등록
                $(this).css({backgroundColor:"yellowgreen"}).text("마우스올라감")
            },mouseout:function(){//mouseout이벤트등록
                $(this).css({backgroundColor:"yellow"}).text("마우스 나감")
            },click:function(){//click 이벤트등록
                $(this)
                .off("mouseover")//.off(이벤트명) : 이벤트핸들러 제거
                .off("mouseout")//자신(test2)의 mouserover,mouserout 이벤트삭제
                .css({backgroundColor:"gray"})
                .text("이벤트제거")
            }
        })
    })
    </script>

 

on메서드 이용 2

 

$("상위요소").on("이벤트명","하위요소선택자(이벤트등록을 위한 요소)",function(){..})
            선택된 상위요소의 하위요소에서 이벤트 발생시 .. 실행

 

<h3>on메서드 이용2</h3>
    <div id="wrap">
        <h4>h4 클릭해보세요</h4>
        <h5>h5 클릭해보세요</h5>
    </div>
    <h5>div 바깥쪽 h5</h5>
    <script>
        $(function(){
            //id=wrap 하위의 h4,h5가 click 시
            $("#wrap").on("click","h4,h5",function(){
                $(this).html("안녕");
            })
            //문서밑의 h5객체가 클릭됐을 때
            $(document).on("click","h5",function(){
                $(this).css("color","pink")
            })
        })
    </script>

 


동적태그에 이벤트적용 ( on함수이용)

    <hr>
    <h3>동적으로 생성된 요소에 이벤트적용</h3>
    <div id="area2" style="border: 1px solid red;">
        <h6>문서에 존재하는 h6요소</h6>
    </div>
    <script>
        //#area2>h6 클릭 시 h6태그 동적 요소 만들기 

   /*1 . 이벤트함수이용
        $(function(){
            $("#area2>h6").click(function(){
                //동적태그 h6에는 이벤트가적용이되지않음
                $("#area2").append("<h6>CLICK을 이용해만들어진 태그</h6>")
            })
        })*/
   
   /* 2. on함수이용
   이것또한 동적태그에는 이벤트등록이안됨
    $("#area2>h6").on("click",function(){
        $("#area2").append("<h6>CLICK을 이용해만들어진 태그</h6>")
    })*/

    // 3. on함수이용(동적태그도 이벤트 등록)
    $("#area2").on("click","h6",function(){
        $("#area2").append("<h6>CLICK을 이용해만들어진 태그</h6>")
    })
    </script>

8-3 ) 일회성이벤트 one

 

$(이벤트대상).one("이벤트타입",이벤트핸들러)

 </script>
    <hr>
    <h3>일회성이벤트 등록</h3>
    <h6 id="test3">딱 한번만 실행</h6>
    <script>
        //one : 단 한번만 사용하는 함수
        $(function(){
            $("#test3").one("click",function(){
                alert("한번 실행 후 다시 실행 안함")
            });
        })
    </script>

 


8-4) 간단예제

keyup이벤트 : 키가 올라올 떄 발생

<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <h3>textarea 태그에 100자까지 입력<br>
        글자를 입력 할 때마다 #remainum 위치에<br>
        만일 입력한내용이 100자를 넘는경우 빨간색글씨의 음수출력
        100자가 안넘는경우는 파란색 숫자로입력
    </h3>
    <p>글쓰기</p><h1 id="remainnum">100</h1>
    <textarea rows="10" cols="70"></textarea>
    
</body>
<script>
    const  a = $("#remainnum").text(); //remainnum의 초기값
    $("textarea").on({keyup:function(){
        let cnt = a-$(this).val().length; // textarea의 length를 계산
        if(cnt>=0){ // 0보다크다면 파란글씨
            $("#remainnum").html(cnt).css({color:"blue"})
        }
        else{//0보다작다면 빨간색글씨
            $("#remainnum").html(cnt).css({color:"red"})
        }
    }})
    

</script>

 


8-5)기본이벤트 무시

 

 event.preventDefault(); 

기본이벤트취소


event.stopPropagation(); 

이벤트전파방지(부모태그의 이벤트를받지않음)

 

둘을 한번에처리하는 방법 :

return false

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <h1><a href="https://www.naver.com">네이버</a></h1>
    <h1>Header 1 </h1>
    <script>
        $(function(){
            $("h1").click(function(){
                $(this).css({backgroundColor:"red"})
            });
            $("a").click(function(event){
                $(this).css({backgroundColor:"blue" , color:"white"})
       
                //event.preventDefault();//기본이벤트취소
                //event.stopPropagation();//이벤트전파방지(부모태그의 이벤트를받지않음)
                return false; //기본이벤트취소 + 이벤트전파방지
            });
        })
    </script>
    
</body>
</html>

 


8-6)이벤트발생요소 검색


                $(this) : 현재마우스커서가있는(이벤트발생객체th태그1개)
                $(this).index()를 할 시 모두똑같은 인덱스가 반환될것임
                $(this).parent() : th태그의 상위태그(tr)
                $(this).parent().children() : tr태그의 하위태그들
                $(this).parent().children().index(this) :
                     th태그들 중 this의 인덱스값 반환

td:nth-child(n)   : (1부터시작)n번쨰 td요소

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table{border-spacing: 0px;
            border-collapse: collapse;}
        .hover{background-color: green; color: yellow;}
        .reverse{background-color: blue; color: wheat;}
    </style>
</head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <table border="1">
        <tr><th>이름</th><th>혈액형</th><th>지역</th><th>성별</th><th>전화</th></tr>
        <tr><td>강민</td><td>AB형</td><td>부산</td><td></td><td>1234</td></tr>
        <tr><td>김지연</td><td> O형</td><td>서울</td><td></td><td>3421</td></tr>
        <tr><td>박승수</td><td>B형</td><td>울산</td><td></td><td>1995</td></tr>
        <tr><td>박민혁</td><td>A형</td><td>경기</td><td></td><td>7721</td></tr>
        <tr><td>이은지</td><td>AB형</td><td>서울</td><td></td><td>1624</td></tr>
        <tr><td>원영</td><td>A형</td><td>충북</td><td></td><td>1884</td></tr>
    </table>
    <script>
        let select;
        $(function(){
            //hover() : moseover , out 둘다처리가능
            $("th").hover(function(){
               //mouseover(마우스를 가져다 댈 때)
                console.log($(this).parent().children().index(this)+1,"위치")
                 select = $(this).parent().children().index(this)+1;
                $(`td:nth-child(${select})`).addClass("hover");
                //td:nth-child(n)   : (1부터시작)n번쨰 td요소

            },function(){//마우스에서 벗어날때 동작(mouseout)
                $(this).remove("hover");//마우스가벗어난 th태그
                $(`td:nth-child(${select})`).removeClass("hover");
                //select번쨰 td요소의 class삭제
            }
        )
        })
    </script>
    
</body>
</html>

 

 


8-7)시각적효과

$("선택자").hide(ms) 

선택자가 ms초에 걸쳐 사라짐

 

$("선택자"). show(ms)

선택자를 ms초에걸쳐 보여줌

 

$("선택자"). toggle(ms)

선택자를 ms초에걸쳐 보여줌

한번 더 클릭시

선택자를 ms초에 걸쳐 사라지게함

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <h3># show() , hide() , toggle()</h3>
    <p>선택된 요소가 점점 커지면서 보여지고 , 점점작아지면서 사라지게하는 메서드</p>
    <button id="hide">숨기기</button>
    <button id="show">보여주기</button>
    <button id="toggle">토글</button>
    <br><br>
    <div id="area" style="background-color: red; width: 100px; height: 100px;"></div>
    <img id="flower" src="../html1/images/flower3.jpg" width="200">
    <script>
        $(function(){
            $("#hide").click(function(){
                //hide(ms) : ms초에 걸쳐  사라짐
                //한번 더 클릭시 변화 X
                $("#flower").hide(1000); 
                $("#area").hide(1000);
            })
            $("#show").click(function(){
                $("#flower").show(1000); 
                $("#area").show(1000);
                //show(ms) : ms초에걸쳐 보여줌
                //한번더 클릭 시 변화없음
            })
            $("#toggle").click(function(){
                $("#flower").toggle(1000); //1초에걸쳐 보여줌
                $("#area").toggle(1000);
                //toggle(ms) : ms에 걸쳐 보여줌 
                // 한번 더 클릭시 ms초에걸쳐 사라짐
            })
        })
    </script>
    
</body>
</html>

 

 


시각적효과2

 

$("선택자").fadeout(ms) 

선택자가 ms초에 걸쳐 사라짐

(불투명->투명)

 

$("선택자"). fadeIn(ms)

선택자를 ms초에걸쳐 보여줌(투명->불투명)

 

$("선택자"). fadeToggle(ms)

선택자를 ms초에걸쳐 보여줌

한번 더 클릭시

선택자를 ms초에 걸쳐 사라지게함

<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <h3># fadeOut() , fadeIn() , FadeToggle()</h3>
    <p>선택된 요소가 점점 커지면서 보여지고 , 점점작아지면서 사라지게하는 메서드</p>
    <button onclick="test1()">숨기기</button>
    <button onclick="test2()">보여주기</button>
    <button onclick="test3()">토글</button>
    <br><br>
    <img id="flower" src="../html1/images/flower1.jpg" width="200">
    <script>
        function test1(){
            $("#flower").fadeOut(2000);
        }
        function test2(){
            $("#flower").fadeIn(2000);
        }

        function test3(){
            $("#flower").fadeToggle(2000);
        }
    </script>

 


시각적효과3

$("선택자").silbling("태그")
                     상위가 선택자인
                    다른 태그들을 선택


  slideUp() : 해당요소를 안보이게한다

    <hr>
    <h3># slideDown() 과 slideUp()</h3>
    <div>Q.반품 언제돼요?</div>
    <p>A. 확인 후에 안내해드리겠습니다</p>
    <div>Q. 상품 위치를 알고싶어요</div>
    <p>A. 배송조회바람</p>
    <div>Q. 현재 이 제품있나요</div>
    <p>A. 네 있어요</p>
    <div>Q. 판매자가연락이안됩니다</div>
    <p>A. 1500-1234로 문의해주세요</p>
    <script>
        $(function(){
            $("div").click(function(){
                const $p = $(this).next(); //클릭된 div의 다음태그(p)
                //$p : jQuery방식 객체(변수명앞에 $를 표시하곤한다.)

                if($p.css("display")=="none"){
                    
                    $(this).siblings("p").slideUp();
                    $p.slideDown();//$p태그만 보이도록하기
                }
                else{ // 클릭된 div의 하위인 $p를 안보이게한다
                    $p.slideUp();
                }

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

클릭시