Frontend - JavaScript(2)


イベントとは?


Webブラウザから通知されたhtml要素のイベントの発生を表します.
JavaScriptは、イベントに応答して特定の操作を実行できます.
JavaScriptを非同期イベント中心のプログラミングモデルと呼ぶ

イベントリスナー


イベント発生時に処理を担当する関数をイベントハンドラと呼ぶ
指定したタイプのイベントがエレメント上で発生した場合、Webブラウザはそのエレメントに登録されたイベントリスナーを実行します.

イベントリスナーをメソッドに転送する方法


ターゲットオブジェクト.addEventListener(「イベント名」、実行するイベントリスナー)
  • 文字上にマウスを置くと背景色が変化する例
  • .
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <script>
    	let p;
    	function init() {// 문서가 완전히 로드되었을때 호출
    		p = document.getElementById("p")
    		//p라는 자바스크립트 변수에 p태그 요소 할당
    		p.addEventListener("mouseover", over) // 이벤트 리스너 등록
    
    		p.addEventListener("mouseout", out) //이벤트 리스너 등록
    
    	}
    	function over() {
    		p.style.backgroundColor = "orchid";
    
    	}
    	function out() {
    		p.style.backgroundColor = "white";
    	}
    </script>
    
    </head>
    <body onload="init()">
     <p id="p">마우스 올리면 orchid 색으로 변경</p>
    
    </body>
    </html>

    over,out関数は別々に設定されていますが、匿名関数では設定せずに使用できます.
  • 匿名関数の例
  • <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <script>
    	let p;
    	function init() {// 문서가 완전히 로드되었을때 호출
    		p = document.getElementById("p")
    		//p라는 자바스크립트 변수에 p태그 요소 할당
    		p.addEventListener("mouseover", function() {
    			this.style.backgroundColor = "orchid";
    		}) // 이벤트 리스너 등록
    
    		p.addEventListener("mouseout", function() {
    			this.style.backgroundColor = "white";
    		}) //이벤트 리스너 등록
    
    	}
    	
    </script>
    
    </head>
    <body onload="init()">
     <p id="p">마우스 올리면 orchid 색으로 변경</p>
    
    </body>
    </html>
    
    上記の例と同様
  • 確認によるページ移動
  • <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <script>
    	function query() {
    		let ret = confirm("네이버로 이동 하시겠습니까?");
    		//confirm은 예,아니오를 선택하는 창이 나온다
    		
    		return ret; // true나 false가 리턴된다
    		
    	}
    	
    	function noAction(e1){
    		e1.preventDefault(); // 이벤트의 디폴트 행동 강제취소
    	}
    	
    </script>
    
    </head>
    <body>
    <a href="http://www.naver.com" onclick="return query()">네이버로 이동 </a>
    <br>
    <form>
     	<input type="checkbox">빵 (체크됨)<br>
     	<input type="checkbox" onclick="noAction(event)">술(체크안됨)
    
    </form>
    
    </body>
    </html>
    
    

    onclick関数にも戻るように書きます.そうしないと、「キャンセル」をクリックしてもページが移動します.

    マウスイベント

  • マウスイベント例
  • 
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <script>
    	let width=1; // 테두리 두께
    	function down(obj) { //클릭한다면
    		obj.style.fontStyle = "italic";
    	}
    	function up(obj){ // 클릭을뗐다면
    		obj.style.fontStyle = "normal";
    	}
    	function over(obj) {  //마우스를 올려놨다면
    		obj.style.borderColor = "violet";
    	}
    	function out(obj) { // 마우스를 밖으로 벗어난다면
    		obj.style.borderColor = "lightgray";
    	}
    	function wheel(e, obj) { // e는 이벤트 객체, obj=span
    		if(e.wheelDelta < 0) { // 휠을 아래로 굴릴 때
    		width--; // 폭 1 감소
    		if(width < 0) width = 0; // 폭이 0보다 작아지지 않게
    		}
    		else // 휠을 위로 굴릴 때
    		width++; // 폭 1 증가
    		obj.style.borderStyle = "ridge";
    		obj.style.borderWidth = width+"px";
    		}
    	
    </script>
    
    </head>
    <body>
    <div>마우스 관련
     <span onmousedown="down(this)"
     onmouseup = "up(this)"
     onmouseover="over(this)"
     onmouseout="out(this)"
     onwheel="wheel(event,this)"
     style="display:inline-block">이벤트</span>가 발생합니다
    
    </div>
    
    </body>
    </html>
    

    マウスをクリックするとフォントが変わり、マウスホイールを回すとborderwidthが大きくなり、スタイルが変わり、逆にborderwidthが小さくなります
  • 画像サイズ例
  • 
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-3.6.0.js">   
    </script>
    <script>
    	function changeImage() {
    		let sel = document.getElementById("sel");
    		let img = document.getElementById("myImg");
    		img.onload = function (){
    			let mySpan = document.getElementById("mySpan")
    			mySpan.innerHTML = img.width + "x" + img.height;
    			
    		}
    		let index = sel.selectedIndex;
    		img.src = sel.options[index].value;
    		
    		
    	}
    </script>
    
    </style>
    
    </head><body onload="changeImage()">
       <form>
       <select id="sel" onchange="changeImage()">
       		<option value="chaewon.jpg">이미지
       		<option value="chaewon1.jpg">이미지1
       		
       </select>
       <span id="mySpan">이미지 크기</span>
       
       </form>
       <p><img id="myImg" src="chaewon,jpg" alt=","></p>
    </body>
    </html>
    

    選択した画像のサイズを表示
  • ラジオボタンの値転送
  • 
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-3.6.0.js">   
    </script>
    <script>
    	function findChecked(){
    		let found = null;
    		let kcity = document.getElementsByName("city");
    		for(let i = 0; i<kcity.length; i++){
    			if(kcity[i].checked == true)
    				found = kcity[i];
    			
    			
    			
    		}
    		if(found != null){
    			alert(found.value + "이 선택되었음");
    		}
    		else{ 
    			alert("선택된것이 없음")
    		}
    	}
    		
    		
    	
    </script>
    
    
    
    </head><body>
       <form>
       	<input type="radio" name="city" value="서울" checked>서울
       	<input type="radio" name="city" value="busan">부산
       	<input type="radio" name="city" value="chunchen">춘천
       	<input type="button" value="find checked" onclick="findChecked()">
       
       
       </form>
    </body>
    </html>
    

    cityというラジオボタン要素の値を入れるkcityを宣言し、for文でkcityのcheckedがtrueの値を検索し、findを入れ、alertでfindの値を出力します.
  • チェックボックス計算機
  • 
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-3.6.0.js">   
    </script>
    <script>
    	let sum = 0;
    	function calc(cBox){
    		if(cBox.checked)
    			sum += parseInt(cBox.value);
    		else
    			sum -= parseInt(cBox.value);
    		
    		document.getElementById("sumtext").value = sum;
    		
    	}
    </script>
    
    
    
    </head><body>
       <form>
       <input type="checkbox" name="hap" value="10000" onclick="calc(this)">모자 1만원
       <input type="checkbox" name="hap" value="30000" onclick="calc(this)">구두 3만원
       <input type="checkbox" name="hap" value="80000" onclick="calc(this)">명품가방 8만원<br>
       지불하실 금액 <input type="text" id="sumtext" value="0">
       
       
       </form>
    </body>
    </html>
    
  • チェックボックスを選択すると、onClickはcalc(this)関数を実行し、dissは値
  • に入ります.
    チェックが
  • if文に設定場合、sum変数の値はマージまたは減算され、値はsumtextテキストボックス
  • に入る.
    //setTimeout & clearTimeout
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>setTimeout()으로 웹 페이지 자동 연결</title>
    </head>
    <body>
    <h3>이미지에 마우스를 올리고 5초간 그대로 있을 때 사이트로 이동합니다</h3>
    <hr>
    <img id="img" src="chaewon.jpg"
    onmouseover="startTimer(5000)"
    onmouseout="cancelTimer()">
    <script>
    let timerID=null;
    function startTimer(time) {
    // 타이머 시작, setTimeout(수행할 함수,밀리초)
    timerID = setTimeout("load('http://www.naver.com')", time);
    // 툴팁 메시지
    document.getElementById("img").title = "타이머 작동 시작...";
    }
    function cancelTimer() {
    if(timerID !=null) 
    clearTimeout(timerID); // 타이머 reset
    }
    function load(url) {
    window.location = url; // 현재 윈도우에 url 사이트 로드
    }
    </script>
    </body>
    </html>
    
  • 画像に写真を載せ、settimeoutメソッドを実行してurl
  • をロードする
  • 画像が飛び出した場合、タイマは
  • にリセットされます.
  • テキストを自動的に回転する方法
  • <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-3.6.0.js">   
    </script>
    
    
    
    
    </head><body>
      <div><span id="span" style="background-color:yellow">
      자동회전하는 텍스트 입니다
      </span></div>
      <script>
       let span = document.getElementById("span");
       let timerID = setInterval("doRotate()",200);
       // 200밀리초 주기로 dorotate()호출 구동된 메소드를 담고있다 함수형 변수
       span.onclick = function (e) {
    	   clearInterval(timerID);
       }
       function doRotate(){
    	   let str = span.innerHTML;
    	   let firstChar = str.substr(0,1)//제일앞에 한글자 가져오기
    	   let remains = str.substr(1, str.length-1); // 한글자 제외한 나머지 담기
    	   str = remains + firstChar;
    	   span.innerHTML = str;
       }
      
        </script>
    </body>
    </html>
    
  • dorotateは、1番目の前にハングル文字を入力、残りの後に文字を貼り付ける方式
  • を繰り返し実行する.
  • 文字をクリックすると、タイマ
  • が初期化されます.