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

279
Views
Javascript: cómo cambiar la clase y el CSS cuando el valor es cero

Tengo 9 cajas en mi html.

Hay un valor, id llamado 'punto de vida'.

Hay una función de clic del mouse: haga clic una vez y disminuya un punto de vida. Este código está completo.

 function decrementlife() { var element = document.getElementById('lifepoint'); var value = element.innerHTML; --value; console.log(value); document.getElementById('lifepoint').innerHTML = value; if(value <= 0) { alert("Game Over!")}; }

Además, hay un estilo css, llamado 'crackbox'.

 .crackbox { position: relative; background: linear-gradient(0deg, black, rgb(120, 120, 120)); width: 12vh; height: 12vh; border-radius: 30%; margin: 5px; }

Quiero cambiar todas las clases de caja de 'caja' a 'crackbox' si el punto de vida es cero. Por lo tanto, todo estilo de caja puede ser 'crackbox'.

El siguiente código falla...

 $(document).ready(function () { $(".box").each(function() { document.getElementById('lifepoint').innerHTML = value; if(value <= 0) { ".box".toggleClass('crackbox') }; }) });
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

La forma más sencilla sería usar querySelectorAll y recorrer los elementos:

 for(let i = 0, list = document.querySelectorAll(".box"); i < list.length; i++) { list[i].classList.toggle('crackbox'); }

O una versión ES6 más corta:

 [...document.querySelectorAll(".box")].forEach(el => el.classList.toggle('crackbox'))
about 4 years ago · Santiago Trujillo Report

0

En lugar de usar el documento listo, llame a otra función desde decrementar la vida si el valor se convierte en 0. Estoy escribiendo el código para su ayuda.

 function decrementlife() { var element = document.getElementById('lifepoint'); var value = element.innerHTML; --value; console.log(value); document.getElementById('lifepoint').innerHTML = value; if(value <= 0) { changeClass(); alert("Game Over!")}; } function changeClass(){ $('.box').addClass('crackbox').removeClass('box'); }

¡¡Espero eso ayude!!

about 4 years ago · Santiago Trujillo 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!