javascript - 鼠标事件侦听器在 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;
}
解决方案
如果您使用事件侦听mouseover
器,则不应该onmouseover
像这样:
square.addEventListener('mouseover', (e) => {
如果你想使用onmouseover
,它应该像这样在html属性中使用
<button onmouseover="functionName()">
on
前缀用于 html 属性,当on
您使用事件侦听器时删除
推荐阅读
- javascript - 检查是否选中了组的任何单选按钮
- javascript - 在 Angular 中调用下一个操作之前等待文件下载事件(Javascript)
- java - compareTo 两个泛型类型
- json - & 号正在破坏 json
- vscode-remote - 使用远程扩展从一台计算机访问文件到另一台计算机
- android - 使用 Android 导航组件将数据传回之前的 Fragment
- xamarin - Catalina 上的 WKWebView 空白
- python - Python排序多维列表第一个元素基于已经排序的第二个元素
- reactjs - 如何使用 ReactJS 从端点获取数据
- python - 如何使用 Python 请求过滤网页上的结果?