jquery - css转场高亮优化

标签 jquery css css-transitions

我正在尝试制作一个动画,以便在js调用上,一个盒子会立即改变颜色,并在缓慢恢复后,我做到了,但我认为这可能不是最佳解决方案:

var d = $('#d1');
d.click(function() {
  d.addClass('high');
  setTimeout(function() {
    d.addClass('trans');
    d.removeClass('high');
    setTimeout(function() {
      d.removeClass('trans');
    }, 1000);
  }, 500);
});
div {
  width: 100px;
  height: 100px;
  background: gray;
}

div.high {
  background: yellow;
}

.trans {
  transition: all 1s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='d1'></div>
<br> click on the box

可以用更少的js/更优化的解决方案来实现吗?

(我在这个演示中使用了 click,但我需要在 js 函数调用上执行此操作)

最佳答案

您可以使用 CSS 动画进行简化:

var d = $('#d1');
d.click(function() {
  d.addClass('high');
  /* No need to remove if you want it to happen one time*/
  setTimeout(function() {
    d.removeClass('high');
  }, 1000);
  /**/
});
div {
  width: 100px;
  height: 100px;
  background: gray;
}

div.high {
  animation: anim 1s ease-in-out;
}

@keyframes anim {
  0%,
  50% {
    background: yellow;
  }
  /* We only specify to 50% so it revert back to initial color 
     and thus can be used with different div having different colors
   */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='d1'></div>
click on the box

关于jquery - css转场高亮优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48619903/

相关文章:

jquery - 图像旋转妨碍事物

Jquery Sortable 不会在更新时发出警报 "order"

jQuery Slider 句柄向左移动

javascript - 将一个圆DIV分成四个扇形DIV

css - 如何将 2 个不同的样式表应用到一个 React 组件?

javascript - CSS3 转换似乎需要 "warmup"时间才能开始?我必须加等待吗?

javascript - 使用 Parsley.js 验证选择的多项选择

javascript - 如何阅读边界半径的实际 CSS 规则

css - Div 目标/主动过渡

html - 为什么我的转换会弹回?