Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created April 15, 2025 12:30
Show Gist options
  • Save sunmeat/9a0f3df533870c38f4eeb343f24cadbb to your computer and use it in GitHub Desktop.
Save sunmeat/9a0f3df533870c38f4eeb343f24cadbb to your computer and use it in GitHub Desktop.
обработка нажатия на клавиши
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Movable Button</title>
<style>
.button {
position: absolute;
left: 10px;
top: 10px;
border: 3px solid green;
padding: 5px;
background-color: yellowgreen;
color: green;
font-family: 'Calibri', sans-serif;
cursor: pointer;
user-select: none;
}
</style>
</head>
<body>
<span id="button" class="button">Нажми на стрелочки!</span>
<script>
class MovableButton {
constructor(elementId) {
this.element = document.getElementById(elementId);
this.x = 10;
this.y = 10;
this.step = 5;
document.addEventListener('keydown', this.handleKeyDown.bind(this));
}
handleKeyDown(event) {
switch (event.key) {
case 'ArrowLeft':
this.x -= this.step;
break;
case 'ArrowRight':
this.x += this.step;
break;
case 'ArrowUp':
this.y -= this.step;
break;
case 'ArrowDown':
this.y += this.step;
break;
case 'h':
case 'H':
case 'р':
case 'Р':
window.close();
return;
}
this.element.style.left = `${this.x}px`;
this.element.style.top = `${this.y}px`;
}
}
new MovableButton('button');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment