[JavaScript] 키보드 입력에 따른 event 처리
2023. 7. 3. 14:16ㆍTip
728x90
텍스트
더보기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
td {
width: 100px;
height: 100px;
border: solid violet 1px;
}
</style>
<script>
let table, row_sel, col_sel
window.onload = function () {
// 3x3 테이블 구조 객체화
table = {
tds: document.getElementsByTagName("td"),
total_rows: 3,
total_cols: 3,
}, row_sel = col_sel = 0
paint(table, row_sel, col_sel, "pink")
}
function paint(table, row, col, color) {
const td_sel = table.tds[row * table.total_rows + col]
td_sel.style.background = color
}
window.onkeydown = function change_location(e) {
paint(table, row_sel, col_sel, "white")
switch (e.key) {
case "ArrowRight": col_sel++; break;
case "ArrowLeft": col_sel--; break;
case "ArrowDown": row_sel++; break;
case "ArrowUp": row_sel--; break;
}
row_sel = (row_sel < 0) ? (table.total_rows - 1) : (row_sel % table.total_rows)
col_sel = (col_sel < 0) ? (table.total_cols - 1) : (col_sel % table.total_cols)
paint(table, row_sel, col_sel, "pink")
}
</script>
</head>
<body>
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
728x90
'Tip' 카테고리의 다른 글
[Java] Singleton Pattern using synchronized (0) | 2023.07.04 |
---|---|
[JavaScript] simple Counter (0) | 2023.07.03 |
[MacOS/zsh] get internal ip from console (0) | 2023.06.29 |
[MacOS] STS3 Spring setting with Eclipse 4.21 (0) | 2023.06.15 |
[MacOS/sdkman] JDK version 관리 (0) | 2023.06.15 |