Frontend - JavaScript(2)
63799 ワード
イベントとは?
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>
チェックが
//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>
<!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>
Reference
この問題について(Frontend - JavaScript(2)), 我々は、より多くの情報をここで見つけました https://velog.io/@jinwoo2025/Frontend-JavaScript2テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol