我有一个元素有一个类,例如.anim.我想实现当用户在移动设备上播放动画时,anim类的元素应该变成蓝色,但在桌面上应该是红色.

这是我迄今为止try 的代码

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>

推荐答案

您不能在@media查询中嵌套@keyframe,但可以嵌套其他动画属性或try 使用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>

Javascript相关问答推荐

从mat—country—select获取整个Country数组

将2D数组转换为图形

我可以从React中的出口从主布局调用一个处理程序函数吗?

Msgraph用户邀请自定义邮箱模板

在拖放时阻止文件打开

在open shadow—root中匹配时,使用jQuery删除一个封闭的div类

Angular 中的类型错误上不存在获取属性

当使用';字母而不是与';var#39;一起使用时,访问窗口为什么返回未定义的?

从Nextjs中的 Select 项收集值,但当单击以处理时,未发生任何情况

按下单键和多值

如果没有页面重新加载Angular ,innerHTML属性绑定不会更新

在表单集中保存更改时删除';禁用';

对具有相似属性的对象数组进行分组,并使用串连的值获得结果

Node.js API-queryAll()中的MarkLogic数据移动

Reaction useState和useLoaderData的组合使用引发无限循环错误

为什么NULL不能在构造函数的.Prototype中工作

使用createBrowserRoutVS BrowserRouter的Reaction路由

使用Perl Selify::Remote::Driver执行Java脚本时出错

检测带有委托的元素内部的点击,以及元素何时按其类名被选中

响应,Use Callback更新状态变量,该变量也存在于其依赖数组中,它如何防止无限重新呈现?