style.top и style.left работают только один раз

Рейтинг: 0Ответов: 1Опубликовано: 14.02.2023

При первом нажатии на KeyD или на KeyS, элемент движется правильно, но при втором элементы перестают двигаться. console.log пишет, что if-ы используются, а KeyA и KeyW вообще не работают. Почему это?

function onMove(event) {
  const coordsPlayer = document.getElementById('player');
  console.log(coordsPlayer.style.top);
  console.log(coordsPlayer.style.left);
  if (event.code === "KeyW") {
    console.log(coordsPlayer.style.top);
    coordsPlayer.style.top -= '25px';
  } else if (event.code === 'KeyD') {
    console.log(coordsPlayer.style.left);
    coordsPlayer.style.left += '25px';
  } else if (event.code === 'KeyA') {
    console.log(coordsPlayer.style.left);
    coordsPlayer.style.left -= '25px';
  } else if (event.code === 'KeyS') {
    console.log(coordsPlayer.style.top);
    coordsPlayer.style.top += '25px';
  } else {
    console.log('why is it not working?');
  }
}
addEventListener('keydown', onMove);

Ответы

▲ 3Принят

Вот как нужно было делать сделать:

let top = 0;
let left = 0;

function onMove(event) {
    const coordsPlayer = document.getElementById('player');

    console.log(coordsPlayer.style.top);
    console.log(coordsPlayer.style.left);

    if (event.code === "KeyW") {
        top -= 25;
    } else if (event.code === 'KeyD') {
        left += 25;
    } else if (event.code === 'KeyA') {
        left -= 25;
    } else if (event.code === 'KeyS') {
        top += 25
    } else {
        console.log('why is it not working?');
    }


    coordsPlayer.style.left = left + 'px';
    coordsPlayer.style.top = top + 'px';
}

addEventListener('keydown', onMove);

Начнём с начала, операторы в JavaScript (+, -, *, /, += и т.д.) не могут чудом понимать величины которые вы используете. В этом можно убедиться:

console.log('25px' + '25px')
console.log('25px' - '25px')
console.log('25px' * '25px')

let n = '25px'

console.log(n + '25px')

Поэтому для чисел к которым потом прибавляется число, обычно заводят переменные, или пропорции для объекта, чтобы уже туда их записывать. Я использовал первый вариант. Убрал также лишние консоль логи, они лишние т.к. логали контент ДО его перезаписи, то есть в логах был тот же контент, что и был указан в первых console.log. Также я перенёс запись стилей в самый низ, чтобы они перезаписывались в любом случае, так мы можем предотвратить лишний повтор кода. И если я написал всё правильно, то всё заработает как часы.