【发布时间】:2021-09-26 18:30:46
【问题描述】:
我正在尝试编写一个简单的 javascript 文件,该文件将随机更改文本的颜色。我将在此时发布我的 js 和 html 文件的位置,但实际上这并不重要,因为它是我经历的第 100 次迭代。
colors.js
class Color {
constructor(name, code) {
this.name = name;
this.code = code;
}
}
const allColors = [
new Color('brightred', '#E74C3C'),
new Color('soothingpurple', '#9B59B6'),
new Color('skyblue', '#5DADE2'),
new Color('leafygreen', '#48C9B0'),
new Color('sunkissedyellow', '#F4D03F'),
new Color('groovygray', '#D7DBDD'),
];
export function getRandomColor() {
return allColors[Math.floor(Math.random() * allColors.length)];
}
export function changeColor() {
var p = document.querySelector("p");
p.style.color = "getRandomColor(code)";
}
export allColors = allColors;
起初我试图在 html 文件中编写 changeColor 函数脚本,但有些东西让我把它放在 javascript 文件中。
index.html
<html>
<head>
<title>Color changer!</title>
</head>
<body>
<h2>External JavaScript</h2>
<button onclick="changeColor()">Change Random Font Color</button>
<p>Randonmly change the color of this font!</p>
<script src = "colors.js">
</body>
<script src = "colors.js"></script>
</html>
我已经浏览了这个 html 文件的几百个不同版本。从我在其上处理 onclick 事件的超级复杂,到像我现在这样的超级简单......我就是想不通。
无论如何,如果有人可以帮助我解决这个问题,我将不胜感激。我真的很想保持它与现在的设置相似(让我了解它是如何工作的,即使我确信有更简单的方法来解决它)。提前谢谢你。
【问题讨论】:
-
像
onclick这样的内联事件处理程序是not recommended。它们是一种obsolete, hard-to-maintain and unintuitive 注册事件的方式。总是useaddEventListener。使用browser console (dev tools)(点击F12)并阅读任何错误。你错过了type="module"。请validate your HTML. -
"getRandomColor(code)"不是颜色。getRandomColor().code是一种颜色。 -
我什至不会费心创建一个类。您只需使用对象或地图将颜色映射到十六进制代码。
标签: javascript html node.js dom-events