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

143
Views
¿Hay alguna forma de cambiar el color de fondo de ::selección (texto seleccionado) usando JavaScript?

Quiero cambiar el fondo de mi selección de texto usando el botón HTML. ¿Hay alguna forma de cambiar el color de fondo de ::selection (texto seleccionado) usando JavaScript?

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

0

En general, cuando no es posible cambiar directamente la configuración de los pseudoelementos a través de JS, es posible establecer variables CSS utilizando JS.

Entonces, si tiene algo como esto en su hoja de estilo:

 ::selection { background-color: var(--selcolor); }

y algo como esto en tu JS:

 element.style.setProperty('--selcolor', selcolor)

funcionará.

Aquí hay un pequeño ejemplo. Cambia la variable de color de selección en el cuerpo:

 function selChange(color) { document.body.style.setProperty('--selcolor', color); }
 body { --selcolor: yellow; } ::selection { background-color: var(--selcolor); }
 <button onclick="selChange('cyan');">Cyan</button> <button onclick="selChange('magenta');">Magenta</button> <button onclick="selChange('yellow');">Yellow</button> <p>Highlight some of this text, then click a color and highlight some text...</p>

about 4 years ago · Juan Pablo Isaza Report

0

  • puede hacerlo alternando la clase, déle a su cuerpo una clase que tomará el estilo de selección predeterminado y creará una clase para alternarlo cuando haga clic en el botón

Aquí hay un ejemplo en CSS puro

 <!DOCTYPE html> <html> <head> <style> .body-selection-green *::selection { background: green; } .body-selection-yellow *::selection { background: yellow } </style> </head> <body class="body-selection-green"> <div> Try to select me </div> <button> change selection background</button> <script> let btn = document.getElementsByTagName("button")[0]; btn.addEventListener("click", function() { if(document.body.classList.contains("body-selection-green")) { document.body.classList.remove("body-selection-green") document.body.classList.add("body-selection-yellow") } else if(document.body.classList.contains("body-selection-yellow")) { document.body.classList.remove("body-selection-yellow") document.body.classList.add("body-selection-green") } }); </script> </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!