
■ JQuery 적용
○ JQuery란?
자바 스크립트 라이브러리로 크로스 브라우징 기능을 가지고 있음
크로스 브라우징은 다양한 브라우저에서 같은 코드로 동일한 동작을 할 수 있게 해줌.
자바 스크립트는 코드가 너무 길어지고 복잡해지는 단점이 있지만
JQuery를 사용하면 같은 기능도 간략하고 단순한 코드로 구현가능
○ JQuery 적용
- JQuery 사이트에서 주소를 복사해서 가져와서 사용
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
</head>
- JS파일 만들어서 JQuery 적용 해도 됨
내용 전체 복사


- JQuery 사용
body에서 아래쪽에 사용 클래스 및 아이디로 된 태그들이 생성전에 실행됨.
body밖에 사용해도 문제는 없음(아래쪽이면)
<body>
<div class="wrap"></div>
<script src="script.js"></script> <!--js파일을 만들어서 적용하기 -->
</body>
<body>
<div class="wrap"></div>
<script> <!--HTML상에 직접 사용하기 -->
$()
</script>
</body>
■ JQuery 사용
○ 기본 불러오기
- document(문서가) ready(준비된후) / 간략하게 앞에를 삭제해도 됨
- function(){} 작성이 안되면 하나의 동작 밖에 사용 못함.
- $는 JQuery를 사용하고 있다는 것을 의미함
$(document).ready(function(){
console.log("일반적 사용");
});
$(function(){
console.log("간략화");
console.log("두개이상");
});

○ JQuery 기본문법
$(function(){
$(선택자).동작함수1().동작함수2();
});
- $ 기호는 제이쿼리를 의미하고, 제이쿼리에 접근할 수 있게 해주는 식별자임
- 선택자를 이용하여 원하는 HTML 요소를 선택하고
- 동작 함수를 정의하여 선택된 요소에 동작을 설정
○ JQuery 객체
JQuery를 사용하기 위해서는 먼저 JQuery 객체를 생성해야함
객체는 여러 메소드를 가지고 있음
<body>
<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
<div class="box" id="box3"></div>
<script src="script.js"></script>
</body>
$(function(){
let ab = $("div");
console.log(ab);
});

· $("div") : div로 된 요소를 선택
· box라는 div 요소가 모두 선택되어 변수 ab에 저장
- 아이디 선택
$(function(){
let ab = $("#box3");
console.log(ab);
});

- Javascript문법
let jsab = document.getElementById('box3'); //id선택
let jsc = document.querySelectorAll(".box"); //모든 box class 선택
■ JQuery 선택자
○ 기본선택자
예제 | 설명 |
$("*") | 모든 요소 선택 |
$(".클래스명") | 지정한 클래스명을 가지는 모든 요소 |
$("#아이디명") | 지정한 아이디명을 가지는 요소 |
$("태그명") | 지정한 태그명을 가지는 모든 요소 |
$("선택자, 선택자") | 지정된 선택자들의 결합 |
○ 자식선택자
예제 | 설명 |
$("div:first-child") | 첫 번째 요소 |
$("div:last-child") | 마지막 요소 |
$("div:nth-child(n)") | n번째 요소 |
$("div:nth-last-child(n)") | 마지막에서 n번째 요소 |
$("div:only-child") | 유일한 자식인 모든 요소 |
<div class="box">
<div id="box1">
<div id="box1-1"></div>
<div id="box1-2"></div>
</div>
<div id="box2">
<div id="box2-1"></div>
<div id="box2-2"></div>
<div id="box2-3"></div>
</div>
<div id="box3">
<div id="box3-1"></div>
</div>
</div>
<div class="box">
<div id="box4"></div>
<div id="box5"></div>
</div>
<div class="box">
<div id="box6"></div>
</div>
$(function(){
console.log($(".box > div:first-child"));
console.log($(".box div:first-child"));
console.log($(".box div:nth-child(2)"));
console.log($(".box div:nth-last-child(2)"));
console.log($(".box div:only-child"));
console.log($(".box > div:only-child"));
});

○ 계층선택자
예제 | 설명 |
$("부모 > 자식") | 부모의 모든 직접 자식요소 |
$("조상 자식") | 조상의 모든 자식 요소 |
$("형제 + 인접") | 형제의 특정 인접 요소 |
$("형제~타입") | 형제의 다음의 타입으로 된 모든 요소 |
인접 이라고 작성 한곳, 타입작성한 곳이 클래스든 태그든 아이디든 상관없음
<div class="box">
<div id="box1">
<div id="box1-1"></div>
<div id="box1-2"></div>
</div>
<div id="box2">
<div id="box2-1"></div>
<div id="box2-2"></div>
<div id="box2-3"></div>
</div>
<div id="box3"></div>
<div id="box4"></div>
<div id="box5"></div>
</div>
$(function(){
console.log($(".box > div"));
console.log($(".box div"));
console.log($("#box1 + div"));
console.log($("#box2 ~ div"));
});

○ JQuery 전용 기본 필터 선택자
예제 | 설명 |
$("선택:odd") | 선택된 홀수번(0,1,2,3)으로 인덱스번호지정 |
$("선택:even") | 선택된 짝수번 요소 |
$("선택:first") | 선택된 첫번째 요소 |
$("선택:last") | 선택된 마지막 요소 |
<div class="box">
<div id="box1">
<div id="box1-1"></div>
<div id="box1-2"></div>
</div>
<div id="box2">
<div id="box2-1"></div>
<div id="box2-2"></div>
<div id="box2-3"></div>
</div>
<div id="box3"></div>
<div id="box4"></div>
<div id="box5"></div>
</div>
$(function(){
console.log($(".box div"));
console.log($(".box div:odd"));
console.log($(".box div:even"));
console.log($(".box div:first"));
console.log($(".box div:last"));
});

○ JQuery 전용 폼 필터 선택자
예제 | 설명 |
$(":button") | type 속성이 button인 요소 |
$(":img") | img 유형의 요소 |
$(":radio") | 라디오 유형의 요소 |
... | 등등 |
<div class="box">
<input type="text" id="a1">
<input type="radio" name="" id="a2">
<input type="radio" name="" id="a3">
<input type="button" value="" id="a4">
</div>
$(function(){
console.log($(":input"));
console.log($(":radio"));
console.log($(":button"));
});

○ JQuery 전용 가시성 필터 선택자
예제 | 설명 |
$("div:hidden") | 숨겨진 요소 선택 |
$("div:visible") | 존재하는 요소 선택 |
<style>
div{
width: 100px;
height: 100px;
background-color: red;
border: 1px solid #000;
}
#box1{
visibility: hidden; /*숨겨지지만 공간은 차지*/
}
#box2{
display: none;
}
</style>
<body>
<div id="box1">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<script src="script.js"></script>
</body>
$(function(){
console.log($("div:visible"));
console.log($("div:hidden"));
});

○ JQuery 전용 함수 필터 선택자
예제 | 설명 |
$("div:eq(n)") | 집합내 인덱스 n에 있는 요소 |
$("div:gt(n)") | 집합내 인덱스 n보다 큰 요소 |
$("div:lt(n)") | 집합내 인덱스 n보다 작은요소 |
$("div:has(p)") | 집합내 지정선택자(p)를 포함하는 요소 |
$("div:animated)") | 애니메이션이 진행 상태에 있는 요소 |
$("div:not(:animated)") | 애니메이션 중이지 않은 요소 |
<div id="box1">
<p id="text1">1</p>
</div>
<div id="box2">2</div>
<div id="box3">3</div>
$(function(){
console.log($("div:eq(1)"));
console.log($("div:gt(0)"));
console.log($("div:lt(2)"));
console.log($("div:has(p)"));
console.log($("div").eq(1));
});

■ Jquery 이벤트
○ click event
$("선택자").click(function(){/* 이벤트 */});
$(selector).animate({properties}, duration, callback);
//속성, 시간, 종료후 실행
$(".box").animate({"width":"200px"}, 2000, function(){});
- 실습예제
<style>
.box{
width: 50px;
height: 50px;
border: 1px solid #000;
}
</style>
<body>
<div class="box" id="box1">1</div>
<div class="box" id="box2">2</div>
<div class="box" id="box3">3</div>
<div class="box" id="box4">4</div>
<script>
$(function(){
$(".box").click(function(){
$(this).animate({"width":"300px","height":"30px"},2000,function(){
$(this).css({"width":"50px","height":"50px"});
});
});
});
</script>
</body>
- 표시와 숨김
<style>
.box{
width: 50px;
height: 50px;
border: 1px solid #000;
}
</style>
<body>
<button id="bt1">숨김</button>
<button id="bt2">보이기</button>
<button id="bt3">토글</button>
<div class="box" id="box1">1</div>
<div class="box" id="box2">2</div>
<div class="box" id="box3">3</div>
<div class="box" id="box4">4</div>
<script>
$(function(){
$("#bt1").click(function(){
$(".box").hide(2000);
});
$("#bt2").click(function(){
$(".box").show("fast");
});
$("#bt3").click(function(){
$(".box").stop().toggle(2000); //stop()멈추고
});
});
</script>
</body>
- 페이드 효과
<script>
$(function(){
$("#bt1").click(function(){
$(".box").fadeOut(1000);
});
$("#bt2").click(function(){
$(".box").fadeIn(1000);
});
$("#bt3").click(function(){
$(".box").stop().fadeToggle(1000); //stop()멈추고
});
});
</script>
- 슬라이드 효과
<script>
$(function(){
$("#bt1").click(function(){
$(".box").slideDown(1000);
});
$("#bt2").click(function(){
$(".box").slideUp(1000);
});
$("#bt3").click(function(){
$(".box").stop().slideToggle(1000); //stop()멈추고
});
});
</script>
- 화면 전환
<style>
.box{
width: 50px;
height: 50px;
border: 1px solid #000;
}
.contents{
height: 300px;
display: none;
background-color: red;
}
</style>
<body>
<button id="bt">토글</button>
<div class="box" id="box1">1</div>
<div class="box" id="box2">2</div>
<div class="box" id="box3">3</div>
<div class="box" id="box4">4</div>
<div class="contents"></div>
<script>
$(function(){
$("#bt").click(function(){
$(".box").stop().slideToggle(0);
$(".contents").stop().slideToggle(0);
});
});
</script>
</body>
○ hover event
$("선택자").hover(function(){},function(){});
$("선택자").hover(function(){
//마우스 올렸을때
},function(){
//마우스 내렸을때
});
- 실습예제
<style>
.box{
width: 50px;
height: 50px;
border: 1px solid #000;
}
</style>
<body>
<div class="box" id="box1">1</div>
<div class="box" id="box2">2</div>
<div class="box" id="box3">3</div>
<div class="box" id="box4">4</div>
<script>
$(function(){
let cbox = $(".box");
let bgc = cbox.css("background-color");
cbox.hover(function(){
$(this).css("background-color","red");
},
function(){
$(this).css("background-color",bgc);
});
});
</script>
</body>
○ 반복적인 실행
- setInterval
setInterval(실행할 것,시간);
- 연습
<style>
.box{
width: 50px;
height: 50px;
border: 1px solid #000;
}
</style>
<body>
<div class="box" id="box1">1</div>
<div class="box" id="box2">2</div>
<div class="box" id="box3">3</div>
<div class="box" id="box4">4</div>
<script>
$(function(){
setInterval(function(){
$(".box").animate({"width":"300px"},1000,"linear")
.animate({"width":"50px"},1000,"linear");
},2000);
});
</script>
</body>
- hover했을때 멈추기
<script>
$(function(){
let boxw;
function stani(){
boxw = setInterval(function(){
$(".box").animate({"width":"100px"},1000,"linear")
.animate({"width":"50px"},1000,"linear");
},2000);
}
stani(); //최초 실행
$(".box").hover(function(){
clearInterval(boxw);
},
function(){
stani();
});
});
</script>
■ Window Scroll
○ 객체의 위치 반환
$("객체").offset();//위치
$("객체").offset().top ; //상단
$("객체").offset().left ; //왼쪽
<style>
.box{
width: 100px;
height: 2000px;
border: 1px solid #000;
}
#box1{
background-color: aqua;
}
#box2{
background-color: red;
}
#box3{
background-color: blue;
}
</style>
<body>
<div class="contents">
<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
<div class="box" id="box3"></div>
</div>
<script>
$(function(){
let box2t = $("#box2").offset();
console.log(box2t);
console.log(box2t.top);
console.log(box2t.left);
});
</script>

○ 스크롤 위치 반환
$(window).scrollTop();
$(function(){
$(window).scroll(function(){
let wst = $(window).scrollTop();
console.log(wst);
});
});

○ 클릭이벤트 스크롤 위치 이동
$("html").scrollTop(300);
- 실제사용
<style>
.box{
width: 100px;
height: 80vh;
border: 1px solid #000;
}
#box1{
background-color: aqua;
}
#box2{
background-color: red;
}
#box3{
background-color: blue;
}
</style>
<body>
<div class="contents">
<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
<div class="box" id="box3"></div>
</div>
<script>
$(function(){
$("#box1").click(function(){
let box2t = $("#box2").offset().top;
$("html").animate({scrollTop:box2t},500);
});
$("#box2").click(function(){
let box1t = $("#box1").offset().top;
$("html").scrollTop(box1t);
});
});
</script>
</body>
■ 찾기 함수
○ 찾기 함수를 알면 이로운 점
$(function(){
$(".hide-con").click(function(e){
e.stopPropagation(); /*나의 부모로 이벤트 전파 방지*/
// if($(this).hasClass("act")){
// $(this).removeClass("act");
// }
// else{
// $(".hide-con").removeClass("act");
// $(this).addClass("act");
// }
$(this).toggleClass("act");
$(this).parent().siblings().children(".hide-con").removeClass("act");
});
$("body").click(function(){
$(".hide-con").removeClass("act");
});
});
■ 찾기 함수
○ 기본화면
<style>
body{
margin: 0;
}
.pbox{
width: 300px;
height: 300px;
display: flex;
background-color: burlywood;
justify-content: space-between;
}
.box{
width: 30%;
align-content: center;
background-color: aqua;
}
.cbox{
width: 50%;
margin: 10px auto;
aspect-ratio: 1;
border-radius: 50%;
background-color: red;
font-size: 30px;
text-align: center;
align-content: center;
}
</style>
<body>
<div class="pbox">
<div class="box">
<div class="cbox">1</div>
<div class="cbox c1">2</div>
<div class="cbox c2">3</div>
</div>
<div class="box">
<div class="cbox">4</div>
<div class="cbox">5</div>
<div class="cbox c1">6</div>
</div>
<div class="box">
<div class="cbox">7</div>
<div class="cbox c2">8</div>
<div class="cbox">9</div>
</div>
</div>
</body>
○ eq(번호) : 찾은 값중 몇번째
○ find(이름) : 모든 자식중에서 이름이 같은것 / 빈것으로 넣을 수 없음
- eq활용 5번찾기
let a = $(".box").eq(1).find(".cbox").eq(1);
○ children(): 모든 자식요소 선택
○ children(이름) : 자식요소 중에서 이름이 같은것
- 0번 박스에서 자식 이름 c1 찾기
let a = $(".box").eq(0).children(".c1");
○ siblings() : 부모가 동일한 나를 제외한 형제
- 0번 박스에서 자식요소 .c1이 아닌 1,3번 찾기
let a = $(".box").eq(0).children(".c1").siblings();
- 모든 박스에서 c1을 형제로 같는 요소 찾기 1,3,4,5
let a = $(".box").children(".c1").siblings();
○ next() : 바로 다음 형제 찾기
○ prev() : 바로 이전 형제 찾기
○ next(이름) , prev(이름) : 이름이 같은것 찾기
- c1으로 되어 있는 클래스의 이전 찾기 1,5번
let a = $(".box").children(".c1").prev();
- c2이전 형제 찾기 2, 7번
let a = $(".box").children(".c2").prev();
- c2이전 형제인데 클래스가 c1 찾기 2번
let a = $(".box").children(".c2").prev();
- c2다음 형제 찾기 9번
let a = $(".box").children(".c2").next();
- 모든 박스들의 첫번째 자식찾기
let a = $(".box").children(":first-child");
let a = $(".box").children(":nth-child(1)");
○ nextAll() : 다음 형제 모두 선택
○ prevAll() : 이전 형제 모두 선택
○ nextAll(이름), prevAll(이름) : 이름이 같은
- 모든 박스들의 첫번째 자식의 다음 형제 모두 (2,3)(5,6)(8,9)번
let a = $(".box").children(":nth-child(1)").nextAll();
- 3번째 이전 형제중 이름이 c2 8번
let a = $(".box").children(":nth-child(3)").prevAll(".c2");
○ parent() : 직전의 부모 / parent(이름) : 직전의 부모중 이름이 같은
○ parents() : 부모 모두 / parents(이름) : 부모 모두 중 이름이 같은
- c1이름을 가진 요소들의 부모 모두 중에서 이름이 .box인 왼쪽 가운데 네모박스
let a = $(".c1").parents(".box");
-C1이름을 가진 요소들의 부모 .box인 요소들 중에서 2번째 자식요소를 제외하고 1,4,3,6번
let a = $(".c1").parents(".box").children(":nth-child(2)").siblings();
-p박스의 자식들중에 c1의 바로 다음요소들 중 c1이전요소 1,5번
let a = $(".pbox").find(".c1").prev();
-box요소중 3번째 이전 요소 모두 중에 자식이 c1인요소 2,6번
let a = $(".box").eq(2).prevAll().children(".c1");
- c1을 클릭했을때 내요소의 부모의 형제들에게 색 노랑 주기
$(".c1").click(function(){
$(this).parent().siblings().css("background-color","yellow");
});
'HTML + CSS > JQuery' 카테고리의 다른 글
JQuery - 숫자 값에 맞는 바 표시하기 (0) | 2025.03.25 |
---|---|
JQuery - 화면에 따른 Html 열기 (0) | 2024.09.24 |
JQuery - 이미지 애니메이션 (0) | 2024.07.23 |
JQuery - 특정 구간 화면 이동 후 효과 실행 (0) | 2024.07.23 |
JQuery - 화면 이동에 따른 회전, 곡선, 이동 (0) | 2024.07.15 |