Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

291
Views
¿Cómo cambiar dinámicamente el color de fondo de entrada?

Tengo un selector de tiempo personalizado como este.

Quiero cambiar el color de fondo de entrada cuando hago clic en él y si hago clic en otro, el fondo anterior debe ser blanco. Pero cuando hago clic en el segundo o en el anterior, etc., no vuelvo al bg normal.

 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>

después de hacer clic para ingresar

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Prueba esto :

 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> ); }
  • (No necesita color de datos)
  • Cree un estado ( currentInput en mi ejemplo) donde almacene el valor actual de la entrada en la que se hizo clic (vea la función onClickFullTime )
  • Cuando el valor de currentInput cambia, useEffect lo pasa a la función changeColor

Demostración: Stackblitz

about 4 years ago · Juan Pablo Isaza Report

0

Si solo se debe configurar uno a la vez, solo asigne a cada botón un atributo de identificación html dinámico (solo botón de tiempo + valor i o algo único) y guárdelo en una variable. Cuando se hace clic en un botón, configure la identificación almacenada (si existe) para que no tenga fondo y también configure el botón en el que se hizo clic para que sea la identificación almacenada, configurando su fondo.

Solo debe realizar un seguimiento de los botones que están resaltados y actualizarlos.

EDITAR: Elaboraré más, se necesita Javascript del lado del cliente para la solución que mencioné anteriormente en el ejemplo del lado del cliente node.js.

Aquí hay un ejemplo que hice para js del lado del cliente simple para resaltar un botón en el que se hizo clic almacenando la identificación y restableciéndola al hacer clic en otra.

 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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!