Перемещение квадрата стрелачками на клавиатуре не работает в чем причина не могу понять
const arrClass = ["red", "green", "yellow", "blue"];
const foo = (el) => {
const i = (arrClass.indexOf(el.className) + 1) % arrClass.length
el.className = arrClass[i];
}
window.addEventListener("keydown", function moveRect(e) {
var rect = document.getElementById("block");
var cs = getComputedStyle(rect);
var left = parseInt(cs.marginLeft);
var top = parseInt(cs.marginTop);
switch (e.keyCode) {
case 37: //влево
rect.style.marginLeft = left - 10 + "px";
break;
case 38: //вверх
rect.style.marginTop = top - 10 + "px";
break;
case 39: //вправо
rect.style.marginLeft = left + 10 + "px";
break;
case 40: //вниз
rect.style.marginTop = top + 10 + "px";
break;
case 32: //SPACE
rect.style.backgroundColor = "blue";
break;
case 13: //ENTER
rect.style.display = "block";
break;
case 27: //ESC
rect.style.display = "none";
break;
}
})
.red {
width: 50px;
height: 50px;
display: inline-block;
margin-left: 15px;
background: red;
}
.green {
width: 50px;
height: 50px;
display: inline-block;
margin-left: 15px;
background: green;
}
.yellow {
width: 50px;
height: 50px;
display: inline-block;
margin-left: 15px;
background: yellow;
}
.blue {
width: 50px;
height: 50px;
display: inline-block;
margin-left: 15px;
background: blue;
}
<div class="red" onclick="foo(this)">
<div id="block"></div>
</div>
Ответы (1 шт):
Автор решения: ksa
→ Ссылка
Перемещение квадрата стрелачками на клавиатуре не работает в чем причина не могу понять
У перемещаемого блока нет размеров. Ты его совсем не видишь.
Я его показал зеленым и добавил ему ширину и высоту.
const arrClass = ["red", "green", "yellow", "blue"];
const foo = (el) => {
const i = (arrClass.indexOf(el.className) + 1) % arrClass.length
el.className = arrClass[i];
}
window.addEventListener("keydown", function moveRect(e) {
var rect = document.getElementById("block");
var cs = getComputedStyle(rect);
var left = parseInt(cs.marginLeft);
var top = parseInt(cs.marginTop);
switch (e.keyCode) {
case 37: //влево
rect.style.marginLeft = left - 10 + "px";
break;
case 38: //вверх
rect.style.marginTop = top - 10 + "px";
break;
case 39: //вправо
rect.style.marginLeft = left + 10 + "px";
break;
case 40: //вниз
rect.style.marginTop = top + 10 + "px";
break;
case 32: //SPACE
rect.style.backgroundColor = "blue";
break;
case 13: //ENTER
rect.style.display = "block";
break;
case 27: //ESC
rect.style.display = "none";
break;
}
})
#block {
width: 10px;
height: 10px;
background: green;
}
.red {
width: 50px;
height: 50px;
display: inline-block;
margin-left: 15px;
background: red;
}
.green {
width: 50px;
height: 50px;
display: inline-block;
margin-left: 15px;
background: green;
}
.yellow {
width: 50px;
height: 50px;
display: inline-block;
margin-left: 15px;
background: yellow;
}
.blue {
width: 50px;
height: 50px;
display: inline-block;
margin-left: 15px;
background: blue;
}
<div class="red" onclick="foo(this)">
<div id="block"></div>
</div>