首页 > 解决方案 > Uncaught ReferenceError : document is not defined

问题描述

I'm javascript beginner and I create this code behind to make an hover effect when a class is hover to affect another class.

But my problem still not here, my problem is when I debug my program I have this message of error in the debuger:

Uncaught ReferenceError: document is not defined

I saw some many question on stackoverflow about this question but I don't understand the awnsers, for examples, what is usefull to install JSDom ? etc...

So I hope I'm not a silly to don't understand, and thanks to support my questions.

const graphic = document.querySelector('.block1');
const audio = document.querySelector('.block3');
const zoomPro = document.querySelector('.zoom');
const zoomPerso = document.querySelector('.zoom2');

zoomPro.addEventListener('mouseenter', () => {
    graphic.classList.add('hoverGraphic');
    audio.classList.add('unhoverAudio');
})

zoomPerso.addEventListener('mouseenter', () => {
    graphic.classList.add('unhoverGraphic');
    audio.classList.add('hoverAudio');
})

zoomPro.addEventListener('mouseleave', () => {
    graphic.classList.remove('hoverGraphic');
    audio.classList.remove('unhoverAudio');
})

zoomPerso.addEventListener('mouseleave', () => {
    graphic.classList.remove('unhoverGraphic');
    audio.classList.remove('hoverAudio');
})
<!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf8">
            <link rel="stylesheet" href="StyleM.css">
            <meta http-equiv="X-UA-Compatible" content="ie-edge">
            <link rel="stylesheet" href="Animation.js">
            <Title>Zeryko - Portfolio</Title>
        </head>
<body>

<div class="mainblock">
    <!-- BOITE 1 -->
        <div class = "block1">
            <header>
                <a class = "zoom" href="PartieVisuelle.html">Professionnel</a>
            </header>
        </div>

    <!-- BOITE 3 -->
    <div class = "block3">
        <footer>
            <a class = "zoom2" href="PartieMusicale.html">Personnel</a>
        </footer>
    </div>
</div>

<!-- BOITE 2 -->
    <div class="BigBlock">
        <div class = "block2">
            <div class="Zeryko">Antoine DOUBLET</div>
            <div class="phrase">Developper & Artist</div>
        </div>
    </div>

</body>
</html>

标签: javascript

解决方案


您的 JavaScript 旨在将事件侦听器添加到 HTML 文档。只有将它嵌入到 HTML 文档中(使用元素)运行它才有意义,<script>以便在加载 HTML 文档时由 Web 浏览器中的 JS 引擎执行。

您的错误消息和提到的 JSDOM 强烈表明您正在尝试使用 Node.js 运行 JS。这没有任何意义。

忘记 Node.js。向 HTML添加一个<script>元素,该元素包含一个src指向 JS 的 URL 的属性。用于defer确保页面已完成解析,以便您正在搜索的 HTML 元素querySelector及时存在。

<script src="....../yourjs.js" defer></script>

推荐阅读