Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

88
Vistas
¿Cómo cambio las pseudoclases en JS?

Tengo un widget de reloj en mi sitio web y quiero que el elemento tenga mi animación :target personalizada tan pronto como se active, sin cambiar el hash.
Lo sé, podría escribir mi código para que la animación :target se reproduzca en el elemento cuando se muestra el widget, pero quiero manipular el elemento para tener la :target .
Básicamente, quiero el mismo efecto que usar un hash en la URL pero sin un cambio de URL.
Firefox DevTools también se basa en HTML y JS, ¿verdad? ¿Cómo lo hicieron?

Aquí está mi animación en un fragmento:

 function initialize() { // Here should the code be that applies the :target pseudo-class to div#uhr... } document.addEventListener('DOMContentLoaded', initialize)
 /* My :target animation */ :target { animation-name: hervorhebungWegenHash; animation-duration: 10s; animation-timing-function: linear; animation-fill-mode: both; } @keyframes hervorhebungWegenHash { 2% { color: black; background-color: orange; } }
 <iframe style="position:fixed;top:0px;left:0px;width:120px;height:120px;border:1px solid #4682b4;border-radius:50%;pointer-events:none;overflow:hidden;" id="uhr" src="https://www.lampe2020.de/widgets/uhr">&nbsp;</iframe> <a href="https://stackoverflow.com/a/46262124/17865928" title="copied 2022-05-26" style="position:absolute;top:125px">This clock widget is also from SO.</a>

Para ver la animación aplicada, vaya a mi sitio web , escriba "uhr" en la página (sin área de texto, solo en la página). De lo contrario, puede verificarlo aplicando #page a mi página principal. Luego, todo el bloque en el medio debe ser naranja y desvanecerse a azul en el transcurso de ~9 segundos.

Actualización: encontré una solución, pero queda una pregunta, por interés:
¿Cómo lo hacen las DevTools?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Finalmente encontré una solución alternativa (no es una solución, pero está bien ...) yo mismo:

 function mimicURLHash(hash) { if (window.location.hash === '#' + hash) { // If the hash is also in the URL, remove it. if (history.replaceState) { history.replaceState("", document.title, window.location.pathname + window.location.search); } else { window.location.hash = ''; } } window.scroll(document.getElementById(hash).getBoundingClientRect().top, document.getElementById(hash).getBoundingClientRect().left); document.getElementById(hash).classList.add('target'); }

Puedes verlo aplicado aquí:

Con esto solo necesito copiar el CSS de la parte :target {} a la parte .target {} . Y luego la función podrá imitar un hash de URL.

 function mimicURLHash(hash) { if (window.location.hash === '#' + hash) { // If the hash is also in the URL, remove it. if (history.replaceState) { history.replaceState("", document.title, window.location.pathname + window.location.search); } else { window.location.hash = ''; } } window.scroll(document.getElementById(hash).getBoundingClientRect().top, document.getElementById(hash).getBoundingClientRect().left); document.getElementById(hash).classList.add('target'); } function initialize() { mimicURLHash('uhr'); // Normally you would feed window.location.hash to it or put it into a click event handler. } document.addEventListener('DOMContentLoaded', initialize)
 /* My :target animation */ /* // The old CSS, no longer needed for this snippet: :target { animation-name: hervorhebungWegenHash; animation-duration: 10s; animation-timing-function: linear; animation-fill-mode: both; }*/ /* This is the CSS we need for this function to work: */ .target { animation-name: hervorhebungWegenHash; animation-duration: 10s; animation-timing-function: linear; animation-fill-mode: both; } @keyframes hervorhebungWegenHash { 2% { color: black; background-color: orange; } }
 <iframe style="position:fixed;top:0px;left:0px;width:120px;height:120px;border:1px solid #4682b4;border-radius:50%;pointer-events:none;overflow:hidden;" id="uhr" src="https://www.lampe2020.de/widgets/uhr">&nbsp;</iframe> <a href="https://stackoverflow.com/a/46262124/17865928" title="copied 2022-05-26" style="position:absolute;top:125px">This clock widget is also from SO.</a>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda