28m28misha10
@28m28misha10
Люблю кодить

Как сделать управление объектом на сайте с клавиатуры?

Есть код:
<p id="moto" style="position:absolute; top:100px; left:0px">1</p>
<input type="button" value="|" onclick="car_down()" style="color: #fff;
  text-decoration: none;
  user-select: none;
  background: rgb(212,75,56);
  padding: .7em 1.5em;
  outline: none;
  border: 1px solid black;">
<input type="button" value="^" onclick="car_up()" style="color: #fff;
  text-decoration: none;
  user-select: none;
  background: rgb(212,75,56);
  padding: .7em 1.5em;
  outline: none;
  border: 1px solid black;">
<input type="button" value="<" onclick="car_left()" style="color: #fff;
  text-decoration: none;
  user-select: none;
  background: rgb(212,75,56);
  padding: .7em 1.5em;
  outline: none;
  border: 1px solid black;">
<input type="button" value=">" onclick="car_right()" style="color: #fff;
  text-decoration: none;
  user-select: none;
  background: rgb(212,75,56);
  padding: .7em 1.5em;
  outline: none;
  border: 1px solid black;">
<div id="qwerty"></div>
<script>
  let windowWidth = window.innerWidth;
  let windowHeight = window.innerHeight;

  function car_down() {
    x = document.getElementById("moto").offsetTop;
    xn = x + 50;
    if (xn > windowHeight) {
      xn = windowHeight - 50;
    }
    document.getElementById("moto").style.top = xn + "px";
  }

  function car_up() {
    x = document.getElementById("moto").offsetTop;
    xn = x - 50;
    if (xn < 50) {
      xn = 50
    }
    document.getElementById("moto").style.top = xn + "px";
  }

  function car_left() {
    x = document.getElementById("moto").offsetLeft;
    xn = x - 50;
    if (xn <= 0) {
      xn = 0;
    }
    document.getElementById("moto").style.left = xn + "px"
  }

  function car_right() {
    x = document.getElementById("moto").offsetLeft;
    xn = x + 50;
    if (xn >= windowWidth) {
      xn = windowWidth - 50;
    }
    document.getElementById("moto").style.left = xn + "px"
  }<code lang="html">
</code>
</script>

Как осуществить передвижение <div id="qwerty"></div>
Через клавиатуру?
Заранее спасибо.
  • Вопрос задан
  • 387 просмотров
Решения вопроса 1
@Valera221
Делаю сайты
Код слишком большой, по этому я упрощу только лишь и сделаю событие нажатия кнопки на клаве тоглько для

для удобства сделаю квадратик (советую проверить и изучить этот скрипт в отдельном файле)
<style>
		#qwerty {
			position: relative;
			width: 500px;
			height: 500px;
			background: black;
		}
	</style>
	<div id="qwerty"></div>


<script>
	
let qwe = document.querySelector("#qwerty");
Тут значения на сколько пикселей в верх
let up = 20;
let b_up = false;
let left = 20;
let b_l = false;

эта функция двигает объект в верх
function go_u () {
	console.log("okU")
	let go = qwe.offsetTop += up;
	qwe.style.top = go + "px";
}
эта функция двигает объект в лево
function go_l () {
	console.log("okL")
	let go = qwe.offsetLeft += left;
	qwe.style.left = go + "px";
}

И так создадим событие нажатие клавиатуры во всем документе
document.addEventListener("keydown",function(e) {
	console.log(e);
если нажал W то запускается функция движения в верх и также в лево
if (b_up) {
go_u();
}else {
	if (e.key == "w") {
		b_up = true;
		go_u();
		// console.log("ok");
	}
}

if (b_l) {
go_l();
}else {
	if (e.key == "d") {
		b_l = true;
		go_l();
		// console.log("ok");
	}
}

})


document.addEventListener("keyup",function(e) {
когда ты отжал кнопку W то мы навсякий случай делаем false, чтобы объект больше не двигался
		console.log(e);
	if (e.key == "w") {
		b_up = false;
		console.log("nopeW");
	}

	if (e.key == "d") {
		b_l = false;
		console.log("nopeD");
	}

})

</script>
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 2
hzzzzl
@hzzzzl
document.addEventListener('keydown', function(e) {
  console.log(e.key)
})


5f0058f84aaec940258128.png

ну а потом сравниваешь e.key с нужными кнопками, и дергаешь нужную функцию для движения
Ответ написан
@olichka1
Сделать управление объектом на сайте с помощью стрелок с клавиатуры, мне помог учебник Ильи Кантора. «Фокусировка: focus/blur». Изображение черного квадрата 50 на 50 пикселей.
<style>
 #qwerty {
      position: relative;
      width: 50px;
      height: 50px;
      background: black;
      cursor: pointer;
    }
    #qwerty:focus {
    	outline: 1px dashed black;
    }
</style>
 <p>Кликните по "изображению" и перемещайте его с помощью клавиш со стрелками.</p>

  <pre id="qwerty">

  <script>
  	 qwerty.tabIndex = 0;
    
    qwerty.onclick = function() {
      this.style.left = this.getBoundingClientRect().left + 'px';
      this.style.top = this.getBoundingClientRect().top + 'px';

      this.style.position = 'fixed';
    };


    qwerty.onkeydown = function(e) {
      switch (e.key) {
        case 'ArrowLeft':
          this.style.left = parseInt(this.style.left) - this.offsetWidth + 'px';
          return false;
        case 'ArrowUp':
          this.style.top = parseInt(this.style.top) - this.offsetHeight + 'px';
          return false;
        case 'ArrowRight':
          this.style.left = parseInt(this.style.left) + this.offsetWidth + 'px';
          return false;
        case 'ArrowDown':
          this.style.top = parseInt(this.style.top) + this.offsetHeight + 'px';
          return false;
      }
    };
	</script>
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы