【问题标题】:Javascript Event Handlers (change font color with a button)Javascript 事件处理程序(使用按钮更改字体颜色)
【发布时间】: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 事件的超级复杂,到像我现在这样的超级简单......我就是想不通。

无论如何,如果有人可以帮助我解决这个问题,我将不胜感激。我真的很想保持它与现在的设置相似(让我了解它是如何工作的,即使我确信有更简单的方法来解决它)。提前谢谢你。

【问题讨论】:

标签: javascript html node.js dom-events


【解决方案1】:

试试

p.style.color = getRandomColor().code;

不带引号,因为你要的是函数的返回值,而不是函数的名字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    相关资源
    最近更新 更多