[26]JavaScript3

JavaScript 이용한 마우스이벤트

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<table border="1" style="border-collapse: collapse;text-align: center;">
    <tr style="cursor: pointer;">
        <td onmouseover="show('k')" id="bar1">KBS</td>
        <td onmouseover="show('m')" id="bar2">MBC</td>
        <td onmouseover="show('s')" id="bar3">SBS</td>
    </tr>
    <tr>
        <td colspan="3">
            <div id="kbs" style="display: block";>
                해피투게더<br>
                <img src="../images/coffee.png">
            </div>
            <div id="mbc" style="display: none";>
                나혼자산다<br>
                <img src="../images/coffee2.png">
            </div>
                <div id="sbs" style="display: none";>
                런닝맨<br>
                <img src="../images/coffee3.png">
            </div>				
        </td>
    </tr>
</table>

JavaScript

마우스를 올리면 이미지 변경 하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function show(kind){
        // alert(kind);
        if(kind=='m'){
            document.getElementById("kbs").style.display = 'none';
            document.getElementById("mbc").style.display = 'block';
            document.getElementById("sbs").style.display = 'none';
            document.getElementById("bar1").style.backgroundColor="#ffffff";
            document.getElementById("bar2").style.backgroundColor="#EB8888";
            document.getElementById("bar3").style.backgroundColor="#ffffff";
        }else if(kind=='s'){
            document.getElementById("kbs").style.display = 'none';
            document.getElementById("mbc").style.display = 'none';
            document.getElementById("sbs").style.display = 'block';
            document.getElementById("bar1").style.backgroundColor="#ffffff";
            document.getElementById("bar2").style.backgroundColor="#ffffff";
            document.getElementById("bar3").style.backgroundColor="#EB8888";
        }else{
            document.getElementById("kbs").style.display = 'block';
            document.getElementById("mbc").style.display = 'none';
            document.getElementById("sbs").style.display = 'none';
            document.getElementById("bar1").style.backgroundColor="#EB8888";
            document.getElementById("bar2").style.backgroundColor="#ffffff";
            document.getElementById("bar3").style.backgroundColor="#ffffff";
        }
    }//show()

01


Audio

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<div style="text-align: center;">
    
    <h1>음악목록</h1>
    
    <img src="../music/gangnamstyle.jpg" width="300px" height="250px" id="poster">
    <br><br>
    <audio id="audio1" src="../music/gangnamstyle.mp3" controls autoplay></audio>
    
</div>

<hr>

<div style="margin: 0 auto; width: 50%;">
    
    <ol>
        <!-- 직접 함수를 링크에 적어 호출할 수 있음(링크는 클릭하니까!) > javascript:loadMusic() 식으로 -->
        <li><a href="javascript:loadMusic('../music/genie.jpg','../music/genie.mp3')">소원을 말해봐</a></li>
        <li><a href="javascript:loadMusic('../music/itaewonfreedom.jpg','../music/itaewonfreedom.mp3')">이태원프리덤</a></li>
        <li><a href="javascript:loadMusic('../music/candy.jpg','../music/candy.mp3')">내귀에 캔디</a></li>
        <li><a href="javascript:loadMusic('../music/gangnamstyle.jpg','../music/gangnamstyle.mp3')">강남스타일</a></li>
    </ol>
    
</div>

JavaScript

1
2
3
4
5
6
7
function loadMusic(jpg,mp3){

    document.getElementById("poster").src=jpg; //"jpg"로 받으면 문자열..!
    document.getElementById("audio1").src=mp3;
    audio1.autoplay();	//자동플레이시키는함수
    
};//loadMusic()

Date객체

  • 날짜 관련 객체 Date객체
  • 현재 시스템의 날짜정보 가져오기
1
var today=new Date();
  • 년월일시분초,요일 값 출력하기
1
2
3
4
5
6
7
today.getFullYear()		//2019
today.getMonth()		//6 기존의 달보다 -1 됨(+1해줘야 원래 달)
today.getDate()			//일
today.getHours()		//시
today.getMinutes()		//분
today.getSeconds()		//초
today.getDay()			//요일 > 0~6일 > 일~토

2019.07.11 (목) PM4:59:06 이런식으로 출력하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
var today=new Date();

var month=today.getMonth()+1;
if(month<10){
    month="0"+month;
}

var date=today.getDate();
if(date<10){
    date="0"+date;
}

var day=today.getDay();
switch (day) {
    case 0:day="일";break;
    case 1:day="월";break;
    case 2:day="화";break;
    case 3:day="수";break;
    case 4:day="목";break;
    case 5:day="금";break;
    case 6:day="토";break;
}

var hour=today.getHours();
if(hour>12){
    hour="PM"+(hour-12);
}else if(hour==12){
    hour="PM"+hour;	//12시부터는 PM이니까 !!
}else{
    hour="AM"+hour;
}

var minute=today.getMinutes();
if (minute<10) {
    minute="0"+minute;
}

var second=today.getSeconds();
if(second<10){
    second="0"+second;	
}

var str=today.getFullYear()+"."+month+"."+date+" "+"("+day+")"+" "+hour+":"+minute+":"+second;

document.getElementById("clock").innerHTML=str;

scope

  • 자바스크립트의 유효범위
  • Local scope (지역변수) - 블라켓기준
    • function 내에 선언된 변수로 function 내에서만 사용 가능
  • Global scope (전역변수)
    • function 외부에서 선언된 변수로 모든 function에서 사용 가능
    • 선언된 시점이 아니라 전역변수가 선언된다면 어디서든 사용할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var one="하나";	//전연변수

function test1(){
    var uid="soldesk";	//지역변수
    alert("uid:"+uid);
    // alert("upw:"+upw); 에러
    alert("one:"+one);
    alert("two:"+two);
    alert("three:"+three);
}//test1()

var two="둘";	//전역변수

function test2(){
    var upw="12345";	//지역변수
    // alert("uid:"+uid); 에러
    alert("upw:"+upw);
    alert("one:"+one);
    alert("two:"+two);
    alert("three:"+three);		
}//test2()

var three="셋";	//전역변수

setTimeout

  • 자주 쓰이고 중요한 함수 ★★★★★
  • 주어진 시간에 따라 자동으로 함수 호출
  • 시간 : 1000 ms = 1 second
  • setInterval(“함수명()”,시간)
    • 주기적으로 호출
  • setTimeout(함수명,시간)
    • 한번만 호출
  • 시간해제
    • clearInterval()
    • clearTimeout()

3초마다 반복적으로 경고창 호출

1
setInterval(function(){alert("Hello")},3000);

3초 후에 경고창을 한 번만 호출

1
setTimeout(function(){alert("Hello")},3000);

재귀적 함수 호출을 이용해서 3초마다 주기적으로 호출

setInterval()과 똑같음

1
2
3
function test(){
    setTimeout(test,3000);
}

JavaScript 이용한 디지털 시계

HTML

1
2
3
4
5
6
7
8
9
<body onload="showtime()" onunload="killtime()">
	<!-- 해당 문서가 시작되는거 onload / 해당 문서를 빠져나가는것 onunload -->
	
	<div id="clock" class="time"></div>
	<hr>
	<input type="button" value="시작" onclick="showtime()">
	<input type="button" value="중지" onclick="killtime()">
	
</body>

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
function showtime(){
    
    var today=new Date();
    
    var month=today.getMonth()+1;
    if(month<10){
        month="0"+month;
    }
    
    var date=today.getDate();
    if(date<10){
        date="0"+date;
    }
    
    var day=today.getDay();
    switch (day) {
        case 0:day="일";break;
        case 1:day="월";break;
        case 2:day="화";break;
        case 3:day="수";break;
        case 4:day="목";break;
        case 5:day="금";break;
        case 6:day="토";break;
    }
    
    var hour=today.getHours();
    if(hour>12){
        hour="PM"+(hour-12);
    }else if(hour==12){
        hour="PM"+hour;
    }else{
        hour="AM"+hour;
    }
    
    var minute=today.getMinutes();
    if (minute<10) {
        minute="0"+minute;
    }
    
    var second=today.getSeconds();
    if(second<10){
        second="0"+second;	
    }
    
    var str=today.getFullYear()+"."+month+"."+date+" "+"("+day+")"+" "+hour+":"+minute+":"+second;
    document.getElementById("clock").innerHTML=str;
    
    //1초후에 showtime함수 호출하기
    //setTimeout("showtime()",1000);	//old version
    timer=setTimeout(showtime,1000);	//추천
    //2) 전역변수에 시간 호출하는 함수를 담기
}//showtime()

var timer;	//1) 전역변수, 어디서든 쓰일 수 있음.(컴파일언어가 아니기 때문에 위치는 상관없음) .
           
function killtime(){
    //시간해제
    clearTimeout(timer);
    //3)onunload 시 clear할 수 있도록 해제하기
}//killtime()

JavaScript 이용한 미니계산기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<form name="calcfrm" id="calcfrm">
    <table class="line">
        <tr>
            <td colspan="4">
                <!-- 입력,출력 결과값 출력상자 -->
                <input type="text" name="result" id="result" size="20" value="0" class="txt" readonly>
            </td>
        </tr>
        <tr>
            <td>
                <input type="button" value="  7	 " onclick="inputData(7)">
            </td>
            <td>
                <input type="button" value="  8	 " onclick="inputData(8)">					
            </td>
            <td>
                <input type="button" value="  9	 " onclick="inputData(9)">					
            </td>
            <td>
                <input type="button" value="  /	 " onclick="operator('/')">					
            </td>
        </tr>
        <tr>
            <td>
                <input type="button" value="  4	 " onclick="inputData(4)">
            </td>
            <td>
                <input type="button" value="  5	 " onclick="inputData(5)">					
            </td>
            <td>
                <input type="button" value="  6	 " onclick="inputData(6)">					
            </td>
            <td>
                <input type="button" value="  *	 " onclick="operator('*')">					
            </td>
        </tr>
        <tr>
            <td>
                <input type="button" value="  1	 " onclick="inputData(1)">
            </td>
            <td>
                <input type="button" value="  2	 " onclick="inputData(2)">					
            </td>
            <td>
                <input type="button" value="  3	 " onclick="inputData(3)">					
            </td>
            <td>
                <input type="button" value="  -	 " onclick="operator('-')">					
            </td>
        </tr>
        <tr>
            <td>
                <input type="button" value="  0	 " onclick="inputData(0)">
            </td>
            <td>
                <input type="button" value="  .	 " onclick="">					
            </td>
            <td>
                <input type="button" value="  =	 " onclick="compute()">					
            </td>
            <td>
                <input type="button" value="  +	 " onclick="operator('+')">					
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="button" value="CLEAR" onclick="cls(this.form)">
            </td>
            <td colspan="2">
                <input type="button" value=" ← " onclick="backspace(this.form)">
            </td>
        </tr>

    </table>
</form>

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
function cls(f){
    // alert(f) [object HTMLFormElement]
    // CLEAR버튼을 클릭하면 name=result 상자에 0을 대입
    f.result.value=0;
}//cls()

function inputData(su){
    var f=document.calcfrm;
    f.result.value=Number(f.result.value+su);
}//inputData()

function backspace(f){
    //마지막글자부터 순차적으로 제거하기
    //일단위값이 있는 상태에서는 0
    var f=document.calcfrm.result;

    // f.value=0;		
    // alert(f.value.length); 길이
    // alert(f.value=f.value.substring(0,f.value.length-1));

    if(f.value.length>1){
        f.value=f.value.substring(0,f.value.length-1);
    }else{
        f.value=0;
    }
}//backspace()

//전역변수 선언
var num1;	//사용자가 입력한 첫번째 수
var num2;	//사용자가 입력한 두번째 수
var op;		//연산자

function operator(kind){
    //1)사용자가 클릭한 연산기호를 op전역변수에 저장
    op=kind;
    //2)현재 name=reult가 가지고 있는 값을 첫번째 수로 저장
    num1=Number(document.getElementById("result").value);
    //3)두번째 수를 입력받기 위해 name=result 상자를 초기화
    document.getElementById("result").value=0;
}//operator()

function compute(){
    //1)연산에 필요한 두번째 수 가져오기
    num2=Number(document.getElementById("result").value);
    //2)연산 후 결과출력
    document.getElementById("result").value=eval(num1+op+num2);
}//compute()

JavaScript 이용한 이미지스크롤

HTML

1
2
3
4
5
6
7
<body onunload="killtime()">

	<div id="myfilm">
		<script>start();</script>
	</div>	
	
</body>

JavaScript

eval()를 이용한 경우

document.write(eval(“"<div id='area”+idx+”' style='position:absolute;top:0px;left:”+(idx*90)+”px'>"”));

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//1) 스크롤 하고자 하는 이미지를 전역변수에 대입
var ctnt=[];	//배열선언
ctnt[0]="<img src='../images/crying.png' width='85'>";
ctnt[1]="<img src='../images/devil.png' width='85'>";
ctnt[2]="<img src='../images/face-glasses.png' width='85'>";
ctnt[3]="<img src='../images/face-grin.png' width='85'>";
ctnt[4]="<img src='../images/face-kiss.png' width='85'>";
ctnt[5]="<img src='../images/face-plain.png' width='85'>";
ctnt[6]="<img src='../images/face-sad.png' width='85'>";
ctnt[7]="<img src='../images/face-smile.png' width='85'>";

//2) 1)에서 준비한 이미지를 id=myfilm에 배치하기
function start(){
    // document.write("<div id='area0' style='position:absolute;top:0px;left:0px'>");
    // document.write(ctnt[0]);
    // document.write("</div>");
    // document.write("<div id='area1' style='position:absolute;top:0px;left:90px'>");
    // document.write(ctnt[1]);
    // document.write("</div>");
    
    for(idx=0;idx<ctnt.length;idx++){
        document.write("<div id='area"+idx+"' style='position:absolute;top:0px;left:"+(idx*90)+"px'>");
        document.write(ctnt[idx]);
        document.write("</div>");
    }
    //3) 3초 후에 scroll함수 1번 호출
    setTimeout(scroll,3000);
}//start()

var img_w=90;//이미지 길이를 변수처리해줌.원래 85px인데 배치할때는 90px로 줬기 때문.

//4) 이미지 스크롤
function scroll(){
    // alert("scroll함수 호출!");
    // alert(document.getElementById("area0").style);
    // alert(document.getElementById("area0").style.left);

    //id=area0의 왼쪽여백값을 가져와서 -10px만큼 줄임
    // var tmp=document.getElementById("area0").style;
    //parseInt로 정수로 변환 후 계산한다
    // tmp.left=parseInt(tmp.left)-10+"px";

    //5) id=area0~id=area7까지 동시에 왼쪽 여백 줄임
    for(idx=0;idx<ctnt.length;idx++){
        var tmp=document.getElementById("area"+idx).style;
        tmp.left=parseInt(tmp.left)-10+"px";
        //7) 이미지 순환
        if(parseInt(tmp.left)<=-img_w){
            tmp.left=(ctnt.length-1)*90+"px";
        }

    }
    //6) 0.5초마다 scroll함수 호출
    timer=setTimeout(scroll,150);
}//scroll()

var timer;

function killtime(){
    clearTimeout(timer);
}//killtime()

BOM

  • The Browser Object Modal (BOM)
    • window , document , location , history ~
      • window.alert() > 확인
      • window.confirm() > 확인/취소
      • document.write() > <body>영역에 출력
      • location.href > 페이지 이동
    • 일반적 기능 객체
      • Number , Math , Date ~

1) 새창 만들기

  • 부모창과 자식창이 서로 독립적 관계
  • window생략가능
  • window.close();
    • 창닫기

modal창

부모창과 자식창을 한 몸으로 하고자 하는 경우

Bootstrap3 Modal Plugin을 활용할 것

1
window.open("url또는파일명","창이름","옵션");

2) 프린터 대화상자 불러오기

1
window.print();

3) 확인true , 취소false

1
2
3
4
5
if (confirm("영구히 삭제됩니다\n지울까요?")) {
    alert("삭제됐습니다.");
}else{
    alert("취소됐습니다");
}

4) device의 해상도 확인

1
2
screen.width
screen.height

5) 페이지 이동

1
2
3
4
5
window.location.href="URL또는파일명";
location="";

location.href="http://www.soldesk.com";
location.reload();	//현재 페이지 새로고침

6) 뒤로,앞으로

1
2
3
history.back();		//뒤로
history.forward();	//앞으로
history.go(-2);

7) 쿠키

  • 웹서버가 사용자에게 저장하는 텍스트 형태의 정보
  • 웹브라우저의 영향을 받는다
    • 예) 아이디저장, 오늘창그만보기
1
document.cookie