首页 > 解决方案 > 鼠标事件侦听器在 vanilla JavaScript 中不起作用

问题描述

我正在开发一个名为“ETCH-A-SKETCH”的简单游戏,即 Odin 项目练习。当鼠标经过方块时,它们应该改变颜色。但我无法让 onmouseover 事件起作用。你认为是什么问题?

索引.html

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <link rel="stylesheet" href="style.css" />
            <title>ETCH-A-SKETCH</title>
        </head>
        <body>
            <div class="container"></div>
    
            <script src="app.js"></script>
        </body>
    </html>

应用程序.js

const body = document.querySelector('body');
const Btn = document.createElement('button');
const container = document.querySelector('.container');
const squares = document.querySelectorAll('.square');
body.append(Btn);
body.insertBefore(Btn, container);
Btn.innerText = 'Create A New Grid';

....

squares.forEach((square) => {
    square.addEventListener('onmouseover', (e) => {
        console.log(e);
        e.preventDefault();
        square.classList.add('zapper');
    });
});

样式.css

.zapper {
    background-color: #fff;
}

.zapper:hover {
    background-color: black;
}

标签: javascripthtmlcss

解决方案


如果您使用事件侦听mouseover器,则不应该onmouseover

像这样:

square.addEventListener('mouseover', (e) => {

如果你想使用onmouseover,它应该像这样在html属性中使用

<button onmouseover="functionName()">

on前缀用于 html 属性,当on您使用事件侦听器时删除


推荐阅读