Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
Establezca el color de fondo <div> al cargar, luego cambie entre 3 colores cuando haga clic

Estoy tratando de establecer el color de fondo de un div al cargar la página en azul. Luego, quiero recorrer 3 colores diferentes (rojo, amarillo y verde) cuando se hace clic y que permanezca el color seleccionado. A continuación se muestra mi código de muestra. Puede ver que los dos primeros no hacen nada cuando se hace clic debido a la configuración del color azul en la carga. No cargué el tercer div en azul al cargar para mostrar cómo quiero que actúe el comportamiento una vez que se hace clic. Cualquier ayuda es apreciada.

 function colorload() { var element = document.getElementById("day1"); element.style.backgroundColor = "blue"; var element = document.getElementById("day2"); element.style.backgroundColor = "blue"; } function changeColor(e, numb) { var color = e.className; e.className = (color == 'red') ? 'amber' : (color == 'amber') ? 'green' : (color == 'green') ? 'red' : 'undefined'; }
 <style onload="colorload()"> .red {background-color:red;} .amber {background-color:yellow;} .green {background-color:green;} div { width:200px; height:100px; margin:50px; text-align: center; vertical-align: middle; line-height: 90px; font-weight:bold; user-select: none; cursor:pointer; } </style>
 <html> <body> <div class="red" id="day1" onclick="changeColor(this, 1)">One</div> <div class="green" id="day2" onclick="changeColor(this, 2)">Two</div> <div class="amber" id="day3" onclick="changeColor(this, 3)">Three</div> </body> </html>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Hice una actualización de sus códigos html y JS , usé en este ejemplo .style en lugar de clases css, si está interesado en usar clases, puede consultar mis comentarios y este enlace en mdn es bastante simple.

archivo html

 <html> <body> <!-- i used .btn class and data-col to play with indexes --> <div class="btn" id="day1" data-col="0" onclick="changeColor(event)">One</div> <div class="btn" id="day2" data-col="0" onclick="changeColor(event)">Two</div> <div class="btn" id="day3" data-col="0" onclick="changeColor(event)">Three</div> </body> </html>

archivo js

 let divs; let colors = ['blue', 'red', 'green' , 'yellow']; // when loading the page, we are catching all divs having the class "btn" // to render it with Blue background document.body.onload = function() { divs = document.querySelectorAll('.btn'); divs.forEach(btn => { const selectedColorIndex = btn.dataset.col; btn.style = 'background:'+colors[selectedColorIndex]; }); }; function changeColor(e) { // catch the clicked div which passed by the "event" value in the html file let divElement = e.target; // get data-col value and convert it to number with (+) const selectedColorIndex = +divElement.dataset.col; // check if we have a next color or get the red index const nextSelectedColor = selectedColorIndex +1 >= colors.length?1:selectedColorIndex+1; // update data-col with the next new color index to conserve the iteration (loop) divElement.dataset.col = nextSelectedColor; // if you want to use classes you can access with // .classList.add(..) and .classList.remove(..) OR // .classList.toggle(..) divElement.style = 'background:'+ colors[nextSelectedColor]; // update the element background with selected color }

También puede reproducir los mismos códigos o actualizar: aquí está el código reproducido completo en JSFiddle que hice para que sea más fácil.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda