如何根据 Javascript 中的用户输入更改文本颜色

问题描述 投票:0回答:1

我想根据用户选择并在提供的输入框中输入的颜色来更改标题的颜色。

我就是不知道如何正确打字

if(用户输入===颜色){

document.getElementById("header").style.color ="that color"

换句话说,如果用户输入等于颜色类型,请将标题颜色更改为指定的颜色。

我不确定将 id 添加到列表中是否有任何帮助,抱歉,这是我在 JS 中的第一个练习

这是 HTML:

    <h1 id="header"> Hi There </h1>

    <p>Choose from one of the following options!</p>

<ul>
    <li id="darkred">Dark red</li>
    <li id = "darkorange">Dark orange</li>
    <li id = "yellow">Yellow</li>
    <li id = "darkgreen">Dark Green</li>
    <li id = "teal">Teal</li>
    <li id = "navy">Navy</li>
    <li id = "indigo">Indigo</li>
    <li id = "fuchsia">Fuchsia</li>
    <li id = "lavender">Lavender</li>
    <li id = "pink">Pink</li>
</ul>
<input type-"text" id="inp"/>

我的意思是我可以为每一种颜色编写函数,这会起作用,但这也会不必要地冗长和愚蠢,我试图在这里制作更通用的函数

javascript function colors user-input textcolor
1个回答
0
投票

您可以创建一个按钮,单击该按钮您将获得

input color
,然后进行设置。

但是,如果您想限制用户只能从列表中选择颜色,那么您可以获取所有颜色,然后从中进行匹配。

const button = document.querySelector("button");
const header = document.getElementById("header");

const allColorsEl = document.querySelectorAll("ul > li");
const allColors = [...allColorsEl].map(el => el.id);

button.addEventListener("click", () => {
  const inputColor = document.querySelector("input").value;
  if (header && inputColor && allColors.find(color => color === inputColor)) {
    header.style.color = inputColor
  } else {
    console.log("Select color from list")
  }
})
<h1 id="header">Hi There</h1>

<p>Choose from one of the following options!</p>

<ul>
  <li id="darkred">Darkred</li>
  <li id="darkorange">Darkorange</li>
  <li id="yellow">Yellow</li>
  <li id="darkgreen">DarkGreen</li>
  <li id="teal">Teal</li>
  <li id="navy">Navy</li>
  <li id="indigo">Indigo</li>
  <li id="fuchsia">Fuchsia</li>
  <li id="lavender">Lavender</li>
  <li id="pink">Pink</li>
</ul>
<input type="text" id="inp" />
<button>change color</button>

© www.soinside.com 2019 - 2024. All rights reserved.