Javascript在本地工作,但不在Github Pages网站上

时间:2018-01-30 08:12:04

标签: javascript html css animation web

我最近为我的网站编写了一些动画,并且它在本地工作得很好,但是第二次我推动它并尝试访问该页面(使用GithubPages托管)它会给我带来错误。 Uncaught TypeError: Cannot read property 'addEventListener' of null(…)
我去了,我做了一些研究,发现了这个页面:https://teamtreehouse.com/community/error-uncaught-typeerror-cannot-read-property-addeventlistener-of-null
而这一个:
Cannot read property 'addEventListener' of null
我尝试应用这些解决方案,但仍然无效。一些解决方案说可能是因为该元素不存在。好吧,因为元素是身体元素,它100%存在并且已经明确定义  我真的希望我没有犯过一些愚蠢的错误!这将是令人尴尬的  JS附在下面,错误发生在document.body.addEventListener("mousemove", function(ev) {

var possibleImages = [
  "assets/images/Moana.jpg",
  "assets/images/GuitarPlaying.png",
  "assets/images/Cheese.jpg",
  "assets/images/CryptoPhoto.jpg",
  "assets/images/LogoSmall.png",
  "assets/images/Group5.jpg"
  ];

document.body.addEventListener("mousemove", function(ev) {
    if (Math.random() < 0.85) {
        return;
    }

    const index = Math.round(Math.random() * possibleImages.length);
    const image = possibleImages[index];

    const el = document.createElement("img");
    document.body.appendChild(el);

    el.classList.add('emoji');
    el.src = image
    el.offsetLeft;  // forces layout

    el.style.left = (event.clientX-410) + 'px';
    el.style.top = (event.clientY-50) + 'px';
    el.style.transform = 'translate(' + (Math.random() * -1000 + 500) + 'px, 1200px) scale(0)';


    el.addEventListener('transitionend', () => {
        el.remove()
})

}, true);

1 个答案:

答案 0 :(得分:1)

问题是您在完全加载之前尝试读取document.body。您可以使用jQuery简单地修复它:

JS:

$( document ).ready(function() {
var possibleImages = [
  "assets/images/Moana.jpg",
  "assets/images/GuitarPlaying.png",
  "assets/images/Cheese.jpg",
  "assets/images/CryptoPhoto.jpg",
  "assets/images/LogoSmall.png",
  "assets/images/Group5.jpg"
  ];

document.body.addEventListener("mousemove", function(ev) {
    if (Math.random() < 0.85) {
        return;
    }

    const index = Math.round(Math.random() * possibleImages.length);
    const image = possibleImages[index];

    const el = document.createElement("img");
    document.body.appendChild(el);

    el.classList.add('emoji');
    el.src = image
    el.offsetLeft;  // forces layout

    el.style.left = (event.clientX-410) + 'px';
    el.style.top = (event.clientY-50) + 'px';
    el.style.transform = 'translate(' + (Math.random() * -1000 + 500) + 'px, 1200px) scale(0)';


    el.addEventListener('transitionend', () => {
        el.remove()
})

}, true);
 }

HTML:

  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>

你可以在没有jQuery的情况下完成它,包括下面写的所有代码:

document.addEventListener("DOMContentLoaded", function(event) { 
  //here your code
});