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?
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>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>