Tengo un elemento que tiene una clase, por ejemplo, .anim . Quiero lograr que cuando el usuario reproduzca la animación en el móvil, el elemento con la clase anim se vuelva azul, pero en el escritorio debería ser rojo. ¿Es posible lograrlo?
Aquí está el código de lo que he intentado hasta ahora
var box = document.getElementsByClassName('box'); document.getElementById("play").addEventListener("click", () => { box[0].classList.add('anim'); }); .box { display: flex; width: 4rem; height: 4rem; border: 1px dashed gray; } .anim { animation-name: rainbow; animation-duration: .25s; animation-timing-function: ease-in-out; } @media only screen and (min-width: 992px) { /* Desktop */ @keyframes rainbow { 0% {background-color: unset;} 100% { background-color: red !important; } } } /* Mobile */ @keyframes rainbow { 0% {background-color: unset;} 100% { background-color: blue; } } <div class="box"></div><br> <button id="play">Play</button>Tuve el mismo problema y terminé resolviendo con el código a continuación, pero mdn desaconseja este enfoque . También aquí hay una lista de posibles valores que puede usar.
windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE']; typeOfOS = window.navigator.platform; if (this.windowsPlatforms.includes(this.typeOfOS)) { //do for windows }No puede anidar un @keyframe en una consulta @media , pero puede anidar otras propiedades de animación o intentar lograr esto con variables css.
.anim { --bg-color: blue; animation-name: rainbow; animation-duration: 0.25s; animation-timing-function: ease-in-out; } @media only screen and (min-width: 992px) { /* Desktop */ .anim { --bg-color: red; } } /* Mobile */ @keyframes rainbow { 0% { background-color: unset; } 100% { background-color: var(--bg-color); } } const box = document.getElementsByClassName('box'); document.getElementById('play').addEventListener('click', () => { box[0].classList.add('anim'); box[0].addEventListener('animationend', event => { event.currentTarget.classList.remove('anim'); }); }); .box { display: flex; width: 4rem; height: 4rem; border: 1px dashed gray; } .anim { --bg-color: blue; animation-name: rainbow; animation-duration: 0.25s; animation-timing-function: ease-in-out; } @media only screen and (min-width: 992px) { /* Desktop */ .anim { --bg-color: red; } } /* Mobile */ @keyframes rainbow { 0% { background-color: unset; } 100% { background-color: var(--bg-color); } } <div class="box"></div> <br /> <button id="play">Play</button>