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

419
Views
¿Cómo crear un botón para ejecutar código al presionar enter o hacer clic en el botón?

He creado un botón. en este momento, el botón solo funciona después de hacer clic en el botón. lo que quiero hacer es, cuando presiono la tecla 'enter' en el teclado o hago clic en el botón, mi código debe ejecutarse.

¿como hacer eso?

 const befoClick= document.querySelector('.befoClick'); const afteClick=document.querySelector('.afteClick'); befoClick.addEventListener('click',()=>{ afteClick.classList.toggle('clicked'); });
 body{ display: grid; place-items: center; height:100vh; } button{ width:200px; height:50px; font-size:20px; cursor: pointer; border:none; border-radius: 8px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .befoClick{ background-color: rgb(74, 74, 255); } .afteClick{ background-color: rgb(67, 255, 77); visibility: hidden; } .clicked{ visibility: visible; } .bfrClick{ visibility: hidden; }
 <div class='allBtn'> <div > <button class='befoClick'>CLICK ME</button> </div> <div > <button class='afteClick'>CLICKED</button> </div> </div>

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

0

Use el detector de eventos keyup y luego verifique la tecla presionada.

Hay dos detectores de eventos, así que agregué una función separada.

 const befoClick= document.querySelector('.befoClick'); const afteClick=document.querySelector('.afteClick'); const toggleClass = () => afteClick.classList.toggle('clicked'); befoClick.addEventListener('click', toggleClass); document.addEventListener('keyup', (event) => { if (event.key === 'Enter') { toggleClass(); } });
 body{ display: grid; place-items: center; height:100vh; } button{ width:200px; height:50px; font-size:20px; cursor: pointer; border:none; border-radius: 8px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .befoClick{ background-color: rgb(74, 74, 255); } .afteClick{ background-color: rgb(67, 255, 77); visibility: hidden; } .clicked{ visibility: visible; } .bfrClick{ visibility: hidden; }
 <div class='allBtn'> <div > <button class='befoClick'>CLICK ME</button> </div> <div > <button class='afteClick'>CLICKED</button> </div> </div>

about 4 years ago · Juan Pablo Isaza Report

0

podemos usar una matriz como ['click', 'keyup] y luego usar forEach en la matriz para escuchar ambos eventos con el mismo eventListener .

Sin embargo, si usa Enter , activará eventListener dos veces, ya que reconoce el clic y presiona Enter. Como tal, necesitamos ejecutar el script y luego también dos veces.

Luego, en el script real, puede usar classList.toggle para alternar entre una clase en la que se hizo clic para aplicar cambios de estilo.

Luego, también puede alternar el textContent de texto del botón entre una matriz.

 var eleButton = document.querySelector('.button'), buttonText = ['CLICK ME', 'CLICKED'], indexButtonText = 0; ['click', 'keyup'].forEach(el => { eleButton.addEventListener(el, function(e) { changeButton(); if (e.key == 'Enter') { changeButton(); } }); }); function changeButton() { indexButtonText = (indexButtonText == 0 ? 1 : 0); eleButton.classList.toggle('clicked'); eleButton.textContent = buttonText[indexButtonText]; }
 body { display: grid; place-items: center; height: 100vh; } button { width: 200px; height: 50px; font-size: 20px; cursor: pointer; border: none; border-radius: 8px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: rgb(74, 74, 255); } .clicked { background-color: rgb(67, 255, 77); }
 <button class='button'>CLICK ME</button>

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!