【问题标题】:How to change input background color dynamically?如何动态更改输入背景颜色?
【发布时间】:2021-10-05 17:58:34
【问题描述】:

我有一个这样的自定义Time-picker。

当我点击它时我想改变输入背景颜色,如果我点击另一个,前一个背景应该是白色的。但是当我点击第二个或等前一个时,不会恢复正常的背景。

  const [hours, setHours] = useState('09')

  const onClickHours = (e) => {
    e.preventDefault();
    setHours(e.target.value)
  }

  const onClickFullTime = (e) => {
    e.preventDefault();
    setFullTime(e.target.value)
    getTime(e.target.value);
    changeColor(e);
  }

  const changeColor = (e) => {
    
      let currentColor = e.target.attributes['data-color'].value;
      let newColor = currentColor === "#fff" ? "#40a9ff" : "#fff";
      e.target.style.backgroundColor = newColor;
      e.target.setAttribute('data-color' , newColor);
  }


  

  const getTime= (fullTime) => {
    onSelectTime(fullTime)
  }

  const hoursArray = [];
  for (let i = 9; i < 22; i++) {
    if (i < 10) {
      i = '0' + i;
    }
    hoursArray.push(
      <input key={i}  onClick={onClickHours} value={i} readOnly />
    )
  }

  const fullTimeArray = [];
  for(let j = 0; j < 60; j = j + 5){
    fullTimeArray.push(hours + ":" + (j< 10 ? '0' + j : j))
  }


              <div className="timepicker">
                <div className="hours">
                  {hoursArray}
                </div>
                <div className="full-time">
                  {
                  fullTimeArray.map((time, index) => (
                    <input name="fullTime" data-color="#fff" key= 
                    {index} onClick={onClickFullTime} value={time} 
                    readOnly/>
                    ))}
                </div>
             </div>

after click to input

【问题讨论】:

  • 您确定 data-color 属性将适用于输入框吗?我不这么认为。
  • 是的,它的工作原理类似于切换。但我不想切换

标签: javascript reactjs antd


【解决方案1】:

试试这个:

import React, { useState, useEffect } from 'react';
import './style.css';

export default function App() {
  const [hours, setHours] = useState('09');
  const [currentInput, setCurrentInput] = useState('');

  const fullTimeArray = [];
  for (let j = 0; j < 60; j = j + 5) {
    fullTimeArray.push(hours + ':' + (j < 10 ? '0' + j : j));
  }

  const onClickFullTime = (e) => {
    e.preventDefault();
    setCurrentInput(e.target.value);
  };

  useEffect(() => {
    changeColor(currentInput);
  }, [currentInput]);

  const changeColor = (current) => {
    const inputElem = document.querySelectorAll("input[name='fullTime']");

    inputElem.forEach((elem) => {
      if (elem.value === current) {
        elem.style.backgroundColor = '#40a9ff';
      } else {
        elem.style.backgroundColor = '#fff';
      }
    });
  };

  return (
    <div className="timepicker">
      <div className="full-time">
        {fullTimeArray.map((time, index) => (
          <input
            name="fullTime"
            key={index}
            onClick={onClickFullTime}
            value={time}
            readOnly
          />
        ))}
      </div>
    </div>
  );
}
  • (不需要数据颜色)
  • 创建一个状态(在我的示例中为currentInput),您可以在其中存储单击输入的当前值(参见onClickFullTime 函数)
  • 当currentInput 的值发生变化时,useEffect 将其传递给changeColor 函数

演示: Stackblitz

【讨论】:

  • 谢谢。有用。但我找到了另一种方法。只需将输入更改为按钮并添加一个动态类名“活动”。它解决了我所有的问题。
  • 是的,使用按钮比输入更容易:)
【解决方案2】:

如果一次只设置一个,只需给每个按钮一个动态的 html id 属性(只是 timebutton + i 值或唯一的东西)并将其存储在一个变量中。单击按钮时,将存储的 id(如果存在)设置为没有背景,并将单击的按钮设置为存储的 id,设置其背景。

您应该只需要跟踪突出显示的按钮并更新它们。

编辑:我将进一步详细说明,我上面提到的 node.js 客户端example 的解决方案需要客户端 Javascript。

这是我为简单的客户端 js 制作的示例,用于突出显示存储 id 并在单击另一个时重置它的单击按钮。

var buttonNumId = ""; // variable for saving the currently highlighted element Id
function myFunction(clickedElement) {
  // unhighlight the current element
  if (buttonNumId !== "") document.getElementById(buttonNumId).style.background = "white";
  // set the currently clicked element and change its color
  buttonNumId = clickedElement.id;
  clickedElement.style.background = "red";
  // update the textbox for demo purposes
  document.getElementById("demo").innerHTML = "Button Id: " + buttonNumId;
}
<!DOCTYPE html>
<html>

<body>

  <h1>Highlight on click</h1>

  <button id="Button1" style="background-color: white;" onclick="myFunction(this)">Click me 1</button>
  <button id="Button2" style="background-color: white;" onclick="myFunction(this)">Click me 2</button>
  <button id="Button3" style="background-color: white;" onclick="myFunction(this)">Click me 3</button>
  <button id="Button4" style="background-color: white;" onclick="myFunction(this)">Click me 4</button>

  <p id="demo"></p>

</body>

</html>

【讨论】:

  • 如果您提供一些带有解释的代码示例,您的答案会更清楚。
  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。
猜你喜欢
  • 2021-03-07
  • 2014-04-05
  • 2013-07-11
  • 2015-12-17
  • 1970-01-01
  • 2014-06-06
  • 2014-12-26
  • 1970-01-01
相关资源
最近更新 更多