在不同设备上以不同方式展示相同的动画
在不同设备上以不同方式展示相同的动画
我有一个带有类名的元素,例如.anim
。我想要实现的效果是,当用户在移动设备上播放动画时,具有anim
类的元素应该变为蓝色,但在桌面上应该变为红色。
这是否可能实现呢?
以下是我迄今为止尝试的代码
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) { /* 桌面 */ @keyframes rainbow { 0% {background-color: unset;} 100% { background-color: red !important; } } } /* 移动设备 */ @keyframes rainbow { 0% {background-color: unset;} 100% { background-color: blue; } }
问题的出现原因是在不同设备上展示相同的动画时,需要根据设备的操作系统类型进行不同的处理。解决方法是使用代码判断设备的操作系统类型,并根据不同的类型执行相应的操作。
以下是解决方法的代码示例:
windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE']; typeOfOS = window.navigator.platform; if (this.windowsPlatforms.includes(this.typeOfOS)) { // 在Windows设备上执行相应的操作 }
但需要注意的是,这种解决方法被MDN(Mozilla Developer Network)不鼓励使用。您可以在这里找到更多相关信息,以及在这里找到可能的操作系统类型值的列表。
CSS 在不同设备上以不同的方式显示相同的动画的问题是由于嵌套查询无效导致的,但可以嵌套其他动画属性或尝试使用 CSS 变量来实现。
解决方法是使用 CSS 变量来设置动画的背景颜色。在动画的开始和结束关键帧中,使用var(--bg-color)来引用 CSS 变量。然后,在媒体查询中定义不同设备上的不同背景颜色。当设备宽度大于等于 992 像素时,将变量--bg-color设置为红色,否则设置为蓝色。
此外,在 JavaScript 中,通过添加和移除类名anim来触发动画。通过监听动画的结束事件animationend,可以在动画结束后移除类名anim。
下面是整理后的代码:
<div class="box"></div> <br /> <button id="play">Play</button>
.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; } } @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'); }); });