Как заставить квадрат двигаться быстрее?
Согласно скрипта имеем квадрат, который перемещается по странице при нажатии стрелочек (верх, вниз, вправо, влево) на клавиатуре. Как сделать так, что бы при комбинации на клавиатуре шифт + стрелочка (верх, вниз, влево, вправо) квадрат начинал двигаться еще быстрее?
<body>
<div id="element"></div>
<script>
let div = document.querySelector("#element");
let distance = 10;
document.addEventListener("keydown", function (e) {
switch (e.code) {
case "ArrowLeft":
moveLeft(div, distance);
break;
case "ArrowRight":
moveRight(div, distance);
break;
case "ArrowUp":
moveUp(div, distance);
break;
case "ArrowDown":
moveDown(div, distance);
break;
}
});
function moveUp(element, distance) {
let top = getComputedStyle(element).top;
element.style.top = parseInt(top) - distance + "px";
}
function moveDown(element, distance) {
let top = getComputedStyle(element).top;
element.style.top = parseInt(top) + distance + "px";
}
function moveLeft(element, distance) {
let left = getComputedStyle(element).left;
element.style.left = parseInt(left) - distance + "px";
}
function moveRight(element, distance) {
let left = getComputedStyle(element).left;
element.style.left = parseInt(left) + distance + "px";
}
</script>
</body>
Ответы (1 шт):
Автор решения: Aleksandr Belous
→ Ссылка
const div = document.querySelector('#element');
const step = 10;
const getPath = (distance, speed, direction) => {
const path = distance * speed;
if (direction === 'left' || direction === 'up') {
return path * -1;
}
return path;
};
const getCoord = (direction) => {
switch (direction) {
case 'left':
case 'right':
return 'left';
case 'up':
case 'down':
return 'top';
default:
throw new Error('getCoord - Invalid direction: ', direction);
}
};
const move = (target, direction, speedMultiplier) => {
const coord = getCoord(direction);
const currentStyles = getComputedStyle(target);
target.style[coord] =
parseInt(currentStyles[coord]) +
getPath(step * speedMultiplier, 1, direction);
};
document.addEventListener('keydown', (ev) => {
if (ev.code.includes('Arrow')) {
const direction = ev.code.slice(5).toLowerCase();
if (ev.shiftKey) {
move(div, direction, 3);
} else {
move(div, direction, 1);
}
}
});
#element {
position: relative;
width: 50px;
height: 50px;
background-color: rebeccapurple;
}
<div id="element"></div>