220714- 제이쿼리 - 이벤트 관련 메소드 (trigger, clearTimeout/clearInterval, preventDefault, stopPropagation, on, 마우스, 키보드, 윈도우)
- +지우개 기능 추가
<style>
#canvas{
border: 3px solid black;
margin-top: 10px;
}
.clear{
display: inline-block;
width: 20px;
height: 20px;
border: 1px solid #ccc;
}
</style>
<script>
$(function(){
var can=document.querySelector('#canvas');
var context=can.getContext('2d');
var position,x,y;
var sw=false;
var lineWidth=1;
var color='#000';
var clearSw=false;
$('.clear').click(function(){
clearSw=!clearSw;
if(clearSw){
$(this).css('border', '3px solid black');
$(can).css('cursor','grabbing');
oldColor=color; //기존 색상은 다른 변수에 넣어두기
oldLinewidth=lineWidth;
color='#fff';
lineWidth=20;
}else{
$(this).css('border', '1px solid #ccc');
$(can).css('cursor','default');
color=oldColor;
lineWidth=oldLinewidth;
}
})
$('select').change(function(){
lineWidth=$('select>option:selected').val();
});
$('button').click(function(){
can.width=can.width; //새로고침-width 새로 들어감
});
$('.colorChange').on('change',function(){
color=$(this).val();
});
$(can).on({ //can에 이벤트 연결
mousedown:function(event){
sw=true;
//console.log('캔버스 위에서 마우스를 누름');
position=$(this).offset(); //현재 위치 좌표값
x=event.pageX-position.left;
y=event.pageY-position.top;
context.beginPath(); //선긋기 준비
context.moveTo(x,y);
},
mousemove:function(){
console.log('캔버스 위에서 돌아다님');
if(sw==true){
position=$(this).offset();
x=event.pageX-position.left;
y=event.pageY-position.top;
context.lineTo(x,y); //선 긋기
context.stroke(); position=$(this).offset();
context.strokeStyle=color; //붓 색상
context.lineWidth=lineWidth; //붓 두께
}
},
mouseup:function(){
//console.log('캔버스 위에서 마우스를 뗌');
sw=false;
}
});
});
</script>
</head>
<body>
<div>
<strong>** 낙서장 **</strong>
<span>붓의 두께</span>
<select name="" id="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<span>붓의 색상</span>
<input type="color" class="colorChange">
<span>지우개</span>
<div class="clear"></div>
<button>새 도화지</button>
</div>
<canvas id="canvas" width="800" height="500"></canvas>
</body>
이벤트 관련 메소드
- trigger : 이벤트 강제 발생
<script>
$(function(){
$('h1').on('click',function(){
$(this).html(function(index, html){
return html+"*";
});
});
setInterval(function(){
$('h1').last().trigger('click');
},2000);
});
</script>
</head>
<body>
<h1>김철수-</h1>
<h1>이영희-</h1>
</body>
- clearTimeout / clearInterval : 해당 이벤트 중지
cf.
setTimeout(함수,밀리초);
setInterval(함수, 밀리초);
<script>
$(function(){
var stop1, stop2;
$('h1').on('click',function(){
$(this).html(function(index, html){
return html+"*";
});
});
stop2=setTimeout(function(){
alert('안녕하세요');
},10000);
stop1=setInterval(function(){ //객체정보 변수에 담기
$('h1').last().trigger('click');
},5000);
$('button').click(function(){
clearInterval(stop1);
clearTimeout(stop2);
});
});
</script>
</head>
<body>
<button>중지</button>
<h1>김철수-</h1>
<h1>이영희-</h1>
</body>
- 이벤트 버블링
: 특정 요소 이벤트가 상위 요소에까지 전달되어 가는 특징
- 버블링
<style>
*{
margin: 5px;
padding: 5px;
border: 3px solid black;
text-decoration: none;
}
</style>
<script>
$(function(){
$('a').click(function(){ //a,h1,body,html 선택
$(this).css('background-color','blue');
});
$('h1').click(function(){ //h1,body,html 선택
$(this).css('background-color','red');
});
});
</script>
</head>
<body>
<h1>
<a href="http://www.kbs.co.kr">한국방송공사</a>
</h1>
</body>
=> a 클릭시 h1 영역도 동작
- 버블링 제거
<style>
*{
margin: 5px;
padding: 5px;
border: 3px solid black;
text-decoration: none;
}
</style>
<script>
$(function(){
$('a').click(function(){
$(this).css('background-color','blue');
//event.preventDefault(); //cf.기본 이벤트 제거 - 링크 이동 X
//event.stopPropagation(); //이벤트 전달 제거
return false; //기본이벤트, 이벤트전달 모두 제거
});
$('h1').click(function(){
$(this).css('background-color','red');
});
});
</script>
</head>
<body>
<h1>
<a href="http://www.kbs.co.kr">한국방송공사</a>
</h1>
</body>
- on
$(부모선택자).on(이벤트이름, 자식선택자, 함수);
=> 현재+미래에 존재하는 객체에 이벤트 발생
=> A선택자 안의 모든 B선택자들에게 이벤트 적용
cf.
$(선택자).on(이벤트이름, 함수);
=> 현재 존재하는 객체에만 이벤트 발생
※ 이전 버전
현재: bind
미래: delegate, live
<script>
$(function(){
/* 현재 객체와만 연결
$('div').on('click',function(){
var len=$('h1').length; //length: 선택자 요소 개수
var targetHTML=$(this).html(); //html 내용 변수에 담기
$('#wrap').append('<h1>'+len+'-'+targetHTML+'</h1>');
//처음 존재했던 h1에 클릭했을 때에만 실행됨 (다른 미래 생성 객체들은 X)
});*/
$('#wrap').on('click','h1',function(){
var len=$('h1').length; //length: 선택자 요소 개수
var targetHTML=$(this).html(); //html 내용 변수에 담기
$('#wrap').append('<h1>'+len+'-'+targetHTML+'</h1>');
});
});
</script>
</head>
<body>
<div id="wrap">
<h1>메르스</h1>
</div>
</body>
- 마우스 이벤트
★mouseenter : 마우스가 요소 경계 외부->내부 이동
★mouseleave : 마우스가 요소 경계 내부->외부 이동
=> 가장 외곽만 경계로 인식 (가장 바깥 요소에서만 발생)
mouseover : 마우스가 요소 안에 들어올 때
mouseout : 마우스가 요소 밖으로 나갈 때
=> 여러 요소들 모두 적용 (버블링)
<style>
.outer{
width: 200px;
height: 200px;
background-color: rgb(255, 220, 154);
margin: 10px; /**/
padding: 50px; /**/
}
.inner{
width: 100%;
height: 100%;
background-color: rgb(255, 99, 120);
}
</style>
<script>
$(function(){
$('.outer').mouseover(function(){
$('body').append('<p>마우스 오버</p>'); // body,outer,inner 왔다갔다 할 때마다 출력
}).mouseenter(function(){
$('body').append('<p>마우스 엔터</p>'); // body,outer 만 인식
})
});
</script>
</head>
<body>
<div class="outer">
<div class="inner">
</div>
</div>
</body>
- 키보드 이벤트
1. keydown : 키보드 누름
2. keypress : 글자 입력됨
3. ★keyup : 키보드 뗌
사용자가 키보드 누름 - keydown 이벤트 발생 - 글자 입력 - keypress 이벤트 발생 - 키보드 뗌 - keyup 이벤트 발생
※ 한글 적용 X
- 문제 : 80자 넘으면 MMS 문구 변경 + 색상 red
<style>
textarea{
resize: none;
}
</style>
<script>
$(function(){
$('textarea').keyup(function(){
var inputlength=$(this).val().length;
//length: 배열/문자열 길이 나타내는 프로퍼티 (함수X)
var remain=80-inputlength;
$('h2').html(remain);
});
});
</script>
</head>
<body>
<div>
<h1>중요메모</h1>
<h2>80</h2>
<textarea name="" id="" cols="70" rows="7"></textarea>
</div>
</body>
- + h2 없애고 p에 글자수 명시
<style>
textarea{
resize: none;
}
div{
width: 160px;
}
p{
text-align: right;
}
</style>
<script>
$(function(){
$('textarea').keyup(function(){
var inputlength=$(this).val().length;
$('p').html(inputlength+"/150");
});
});
</script>
</head>
<body>
<div>
<h1>중요메모</h1>
<!-- <h2>80</h2> -->
<textarea name="" id="" cols="20" rows="5" maxlength="150"></textarea> ////
<p></p>
</div>
</body>
- 윈도우 이벤트
- resize, scroll
<script>
$(function(){
$(window).resize(function(){
//윈도우 사이즈 바뀌면 코드 실행
});
for(var i=0;i<25;i++){
$('<h1>무한 c체험</h1>').appendTo('body');
}
$(window).scroll(function(){
var scrollH=$(window).scrollTop()+$(window).height(); //스크롤막대 좌표 + 나머지 문서 높이
var docH=$(document).height();
//scrolltop:스크롤 막대 top 좌표 (가변적)
//window.height: 창의 길이 (문서 전체-스크롤)
//document.height: 문서 전체 높이
if(scrollH>=docH-200){
$('<h1>무한 스크롤 완성</h1>').appendTo('body');
}
});
});
</script>
</head>
<body>
<h1>윈도우 이벤트</h1>
</body>
- 문제
+ 버튼 누르면 글꼴 1씩 증가(~30) / - 는 그 반대 (8~)
100% 버튼 누르면 최초 글자크기로 (16)
<script>
$(function(){
// 내 답변
// var fontS=16;
// $('#zoom button').click(function(){
// i=$(this).index();
// if (i==0){
// fontS--;
// }else if (i==1){
// fontS=16;
// }else{
// fontS++;
// }
// $('.font').html(fontS+'px');
// $('#wrap').css('font-size',fontS);
// });
var baseFont=16;
$('#zoom button').on('click',function(){
i=$(this).index();
if($(this).hasClass('zoomout')){
if (baseFont<=8) return false; baseFont--;
}else if($(this).hasClass('zoomin')){
if (baseFont>=30) return false; baseFont++;
}else{
baseFont=16;
}
$('.font').text(baseFont+'px');
$('#wrap').css('font-size',baseFont);
});
});
</script>
<body>
<p id="zoom">
<button class="zoomout">-</button>
<button class="base">100%</button>
<button class="zoomin">+</button>
</p>
<p class="font">
16px
</p>
<div id="wrap">
목요일인 내일(14일)은 오전 중 전국 대부분 지역에서 장맛비가 그치겠지만
제주도는 모레(15일) 밤까지 가끔 비가 오겠다.
</div>
</body>