1. Event 등록
이벤트 등록은 직접 등록과 on 을 통한 등록이 있다.
J-Query 에서 사용하는 이벤트는 아래와 같다.
| expression | description |
| click() | 클릭 시 발생 |
| dblclick() | 더블 클릭 시 발생 |
| mouseenter() | 마우스가 특정 영역으로 들어왔을 경우 발생 |
| mouseleave() | 마우스가 특정 영역 밖으로 나갔을 경우 발생 |
| mousedown() | 마우스 버튼 눌렀을 경우 발생 |
| mouseup() | 마우스 버튼 떼었을 경우 발생 |
| hover() | 마우스 오버 시 발생 (mouseenter 와 mouseleave 를 결합한 형태) |
| focus() | 포커스가 들어왔을 시 발생 |
| blur() | 포커스를 잃었을 경우 발생 (웹 접근성 상 사용 금지) |
더 알고 싶다면 API 사이트(http://api.jquery.com/category/events/) 참고 하자
<html>
<head>
<meta charset="UTF-8">
<title>J-QUERY</title>
<link rel="icon" href="../img/chrome.png">
<!--Content Delivery Network 방식-->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="btn">버튼생성</button>
<button id="evtDel">이벤트 삭제</button>
<div style="margin: 10px;"></div>
</body>
<script>
// $(셀렉터).on('이벤트',실행함수);
$('#btn').on('click',function(){
$('div').append('<button onclick="clickEvt()">click</button>');
$('div').append('<button class="newBtn">click2</button>');
/* 이벤트가 실행 되었을 때 생성된 버튼이 이벤트를 걸어준다.
이벤트가 요소에 중복적용 될 수 있다.
$('div button').click(function(){
alert('click');
});
*/
});
// $(셀렉터).이벤트(실행함수);
$('#evtDel').click(function(){
$('#btn').off('click');// on 으로 추가된 이벤트는 off 로 삭제 가능
});
//새로생긴 버튼을 누르면 alert('click') 이 나타나도록 해 보자
console.log($('div button'));
/* 아래 방법으로는 안된다.(이 구문을 읽기 시작할 때는 버튼이 아직 없다.)
$('div button').click(function(){
alert('click');
});
*/
// 1. on 속성을 이용하는 방법
function clickEvt(){
alert('click');
}
// 2. document 에 이벤트를 건다.
//$(셀렉터).on(이벤트,타겟,실행함수);
$(document).on('click','.newBtn',function(){
alert('click2');
});
</script>
</html>
<html>
<head>
<meta charset="UTF-8">
<title>J-QUERY</title>
<link rel="icon" href="../img/chrome.png">
<!--Content Delivery Network 방식-->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
div{
width: 200px;
height: 200px;
margin: 10px;
text-align: center;
float: left;
}
#mousezone{
background-color: lightseagreen;
}
#overzone{
background-color: orange;
}
#login_zone{
clear: left;
text-align: left;
width: 300px;
}
</style>
</head>
<body>
<p>클릭하면 글자 색상이 바뀝니다.</p>
<p>클릭하면 글자 색상이 바뀝니다.</p>
<p>클릭하면 글자 색상이 바뀝니다.</p>
<p>클릭하면 글자 색상이 바뀝니다.</p>
<div id="mousezone">마우스 존</div>
<div id="overzone">H-OVER ZONE</div>
<div id="login_zone">
ID : <input type="text"/>
<br/>
PW : <input type="text"/>
</div>
</body>
<script>
$('p').on('click',function(){
console.log('click');
$(this).css({'color':'red'});
});
$('p').on('dblclick',function(){
$(this).css({'color':'black'});
});
/*
$('#mousezone').on('mouseenter',function(){
$(this).css({'background-color':'yellow'});
});
$('#mousezone').on('mouseout',function(){
$(this).css({'background-color':'lightseagreen'});
});
*/
$('#mousezone').on({
mouseenter:function(){
$(this).css({'background-color':'yellow'});
},
mouseout:function(){
$(this).css({'background-color':'lightseagreen'});
},
mousedown:function(){
$(this).css({'background-color':'yellowgreen'});
},
mouseup:function(){
$(this).css({'background-color':'yellow'});
}
});
// hover : enter + out
$('#overzone').hover(function(){
$(this).css({'background-color':'red'});
},
function(){
$(this).css({'background-color':'orange'});
});
$('input').on({
focus:function(){
$(this).css({'background-color':'violet'});
},
blur:function(){
$(this).css({'background-color':'white'});
}
});
</script>
</html>
2. Get, Set
Object 는 Attribute 를 갖는다.(member 라고도 한다.)
Dom 객체 에서도 객체를 갖는다.
J-Query 에서는 JS 와 마찬가지로 이 속성을 다룰 수 있다.
| $(셀렉터).attr("지정 속성", "변경 내용") | 해당 요소의 지정된 속성을 변경한다. |
| $(셀렉터).val("변경 내용") | 해당 요소의 값 (value) 을 변경한다. |
| $(셀렉터).text("변경 내용") | 해당 요소의 텍스트 값을 변경한다. (내부 html 태그 미포함) |
| $(셀렉터).html("변경 내용") | 해당 요소의 텍스트 값을 변경한다. (내부 html 태그 포함) |
<html>
<head>
<meta charset="UTF-8">
<title>J-QUERY</title>
<link rel="icon" href="../img/chrome.png">
<!--Content Delivery Network 방식-->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input type="text" value="some text"/>
<p>문자가 <b>강조된</b> 영역</p>
<span id="txt"></span>
<span id="html"></span>
<fieldset>
<legend>숫자 입력</legend>
RANGE(0~100) :
<input type="range" min="0" max="100" value="30" step="1"/>
당신이 선택한 값 : <span id="msg"></span>
<br/>
<button id="inc">증가</button>
<button id="dec">감소</button>
</fieldset>
<fieldset>
<legend>라디오 버튼</legend>
<div>
<input type="radio" name="front" value="HTML">HTML
</div>
<div>
<input type="radio" name="front" value="CSS">CSS
</div>
<div>
<input type="radio" name="front" value="JS">JS
</div>
<span id="selected">선택값 없음</span>
</fieldset>
</body>
<script>
// 특정 속성 값 가져오기
var attr = $('input[type="text"]').attr('type');
console.log(attr);
// 특정 값(value 속성) 가져오기
var val = $('input[type="text"]').val();
console.log(val);
// 수정할 때는 수정할 값이 들어가야 한다.
$('input[type="text"]').attr('type','password');
var html = $('p').html(); // 태그를 살려서 가져온다.
var text = $('p').text(); // 태그를 무시하고 가져온다.
console.log(html,'==',text);
// 문자가 <b>강조된</b> 영역 == 문자가 강조된 영역
// html() : 태그 효과를 살려서 적용한다.
$('#html').html('<h1>html() 과 text() 의 차이</h1>');
// text() : 태그를 단순 텍스트 취급한다. (효과 없음)
$('#txt').text('<h1>html() 과 text() 의 차이</h1>');
var val = $('input[type="range"]').val();
$('#msg').text(val);
// $('input[type="range"]').on('mouseup',function(){
// $('#msg').html($(this).val());
// });
$('input[type="range"]').mousedown(function(){
$(this).on('mousemove',function(){
$('#msg').html(val);
});
});
$('input[type="range"]').mouseup(function(){
$(this).off('mousemove');
});
// val += 1 이건 왜 안되는지?
$('#inc').click(function(){
val++;
$('input[type="range"]').val(val);
$('#msg').html(val);
});
$('#dec').click(function(){
val--;
$('input[type="range"]').val(val);
$('#msg').html(val);
});
// $('input[type="radio"]')
$(':radio').click(function(){
var val = $(this).val();
$('#selected').html(val);
});
</script>
</html>
<html>
<head>
<meta charset="UTF-8">
<title>J-QUERY</title>
<link rel="icon" href="../img/chrome.png">
<!--Content Delivery Network 방식-->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input type="text" value="홍길동"/>
<button>속성 변경</button>
<div></div>
</body>
<script>
$('button').click(function(){
$('input[type="text"]').attr('type','button');
$('input[type="button"]').val('클릭!');
$('input[type="button"]').attr('onclick','alert("OK")');
});
// append() : 해당 자식 요소의 맨 마지막에 컨텐츠를 붙이는 함수
$('div').append('<input type="button" onclick="test(123)" value="click"/>');
// test('param')
// var param = 'param';
// escape 문자 : 특수 능력을 가진 문자열의 특수 능력을 무력화하는 문자 (대상 문자 앞에 넣어준다.)
$('div').append('<input type="button" onclick="test(\'param\')" value="click"/>');
function test(arg){
alert(arg);
}
</script>
</html>
3. CSS
비교적 단순한 스타일 적용에 활용 한다.
특정 스타일을 확인 하거나 변경할 경우 사용 한다.
| $(셀렉터).css("attribute") | 선택한 요소의 스타일 값을 받아온다. |
| $(셀렉터). css("attribute", "value") | 선택한 요소의 스타일 값을 변경한다. |
<html>
<head>
<meta charset="UTF-8">
<title>J-QUERY</title>
<link rel="icon" href="../img/chrome.png">
<!--Content Delivery Network 방식-->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="ex1" style="color: blue; font-size: 32px;">스타일 적용</p>
<p id="ex2">스타일 미적용</p>
<div>
font size : <span id="size"></span><br/>
font color : <span id="color"></span><br/>
<button>css 적용</button>
</div>
</body>
<script>
var color = $('#ex1').css('color');
var size = $('#ex1').css('font-size');
$('#size').html(size);
$('#color').html(color);
$('button').click(function(){
//$('#ex2').css('color',color);
//$('#ex2').css('font-size',size);
$('#ex2').css({
'color':color,
'font-size':size
});
});
</script>
</html>
4. AddClass
이미 선언된 클래스를 적용/삭제 할 경우 사용한다.
비교적 복잡한 스타일을 사용 할 경우 유용하다.
| $(셀렉터).addClass(" class name ") | 선택한 요소에 해당 클래스 추가 |
| $(셀렉터).removeClass(" class name ") | 선택한 요소에 해당 클래스 삭제 |
| $(셀렉터).toggleClass(" class name ") | 선택한 요소에 해당 클래스 추가 / 삭제 |
<html>
<head>
<meta charset="UTF-8">
<title>J-QUERY</title>
<link rel="icon" href="../img/chrome.png">
<!--Content Delivery Network 방식-->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
.ex{
background-color: cadetblue;
text-align: center;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<button id="add">클래스 추가</button>
<button id="remove">클래스 삭제</button>
<button id="toggle">클래스 토글</button>
<div>DIV</div>
</body>
<script>
//addClass('클래스이름')
//removeClass('클래스이름')
//toggleClass('클래스이름')
$('button').on('click',function(){
switch($(this).attr('id')){
case 'add':
$('div').addClass('ex');
break;
case 'remove':
$('div').removeClass('ex');
break;
/*
case 'toggle':
$('div').toggleClass('ex');
break;
*/
}
});
$('#toggle').click(function(){
$('div').toggleClass('ex');
/*
var sw = $('div').attr('class');
if(sw == 'ex'){
$(this).html('remove');
}else{
$(this).html('add');
}
*/
// class 보유 여부를 true/false 로 반환
var sw = $('div').hasClass('ex');
if(sw){
$(this).html('remove');
}else{
$(this).html('add');
}
});
</script>
</html>
'J-Query' 카테고리의 다른 글
| 05. 요소 추가, 요소 삭제, 요소 면적 (0) | 2024.03.24 |
|---|---|
| 04. Animate, Method Chainin (0) | 2024.03.24 |
| 03. hide & show, Fade effect, Slide (0) | 2024.03.24 |
| 01. J-Query의 기초 (0) | 2024.03.11 |