Невозможно прочитать свойство 'style' из null, даже если я добавил position: absolute; - PullRequest
0 голосов
/ 24 марта 2020

Я довольно новичок в кодировании. Я пытаюсь выучить HTML, CSS и Javascript, просто создав гоночную игру в браузере. Я сделал функции для управления автомобилем, но эти сообщения об ошибках возвращаются каждый раз, когда я нажимаю кнопку:

Cannot read property 'style' of null

Это мой код

var car = document.getElementById('car');
var container = document.getElementsByClassName('container');


var carLeft = 0;

function anim(e) {
  if (e.keyCode==87) {
    //W

  }

    if (e.keyCode==65) {
      //A
      carLeft+=2;
      car.style.left = carLeft + 'px';
  }

    if (e.keyCode==83) {
      //S

  }

    if (e.keyCode==68) {
      //D
      carLeft-=2;
      car.style.left = carLeft + 'px';
  }
}

document.onkeydown =anim;

Это мой css

#car {
    background-color: blue;
    height: 10px;
    width: 20px;
    z-index: 10;
    position: absolute;
    left: 0;

}

Ответы [ 2 ]

0 голосов
/ 24 марта 2020

Я думаю, что использование querySelector будет лучшим вариантом, который решит проблемы, которые у вас возникают

var car = document.querySelector('#car');
var container = document.querySelector('.container');


var carLeft = 0;

function anim(e) {
  if (e.keyCode==87) {
    //W

  }

    if (e.keyCode==65) {
      //A
      carLeft+=2;
      car.style.left = carLeft + 'px';
  }

    if (e.keyCode==83) {
      //S

  }

    if (e.keyCode==68) {
      //D
      carLeft-=2;
      car.style.left = carLeft + 'px';
  }
}

document.onkeydown = anim;
#car {
    background-color: blue;
    height: 10px;
    width: 20px;
    z-index: 10;
    position: absolute;
    left: 0;

}
<div class="container">
  <p id="car">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>
</div>

Было бы очень полезно, если бы вы могли также предоставить свою версию html, а также сообщить мне, помог ответ или нет чтобы я мог улучшить его для вас.

0 голосов
/ 24 марта 2020
Переменная

car - это набор объектов с именем класса «контейнер».

var car = document.getElementById('car');
var container = document.getElementsByClassName('container')[0];//use this way


var carLeft = 0;

function anim(e) {
  if (e.keyCode==87) {
    //W

  }

    if (e.keyCode==65) {
      //A
      carLeft+=2;
      car.style.left = carLeft + 'px';
  }

    if (e.keyCode==83) {
      //S

  }

    if (e.keyCode==68) {
      //D
      carLeft-=2;
      car.style.left = carLeft + 'px';
  }
}

document.onkeydown = anim;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...