性能友好的闪烁效果

时间:2017-04-21 10:35:52

标签: javascript jquery css

我很想添加这样的闪烁效果,但我认为setInterval对于仅仅是化妆品的东西来说太过分了:

jQuery(function(){
  $("#watch").each(function(){
    var $box = $(this);
    var show = true;
    setInterval(function(){
      var m = moment();
      $box.text(show ? m.format('H:mm') : m.format('H mm'));
      show = !show;
    }, 500);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src='//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js'></script>
<div id="watch">--:--</div>

我可以使用更新的JavaScript API,还是CSS过渡?

2 个答案:

答案 0 :(得分:1)

使用this回答提供的CSS,您可以执行此操作

&#13;
&#13;
jQuery(function() {
  $("#watch").each(function() {
    var $box = $(this);
    setInterval(function() {
      var m = moment();
      $box.html(m.format('H') + '<span class="blink_me">:</span>' + m.format('mm'));
    }, 1000);

  });
});
&#13;
.blink_me {
  animation: blinker 1s infinite;
}

@keyframes blinker {
  50% {
    opacity: 0;
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src='//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js'></script>
<div id="watch">--:--</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

对于记录,这是我根据George's answer编写的最终CSS:

&#13;
&#13;
section {
  font-size: 5rem;
}

.stop-watch span {
   animation: blink 1s infinite;
}

@keyframes blink{
  0% {
    animation-timing-function: steps(1, end);
    opacity: 1;
  }
  50% {
    animation-timing-function: steps(1, end);
    opacity: 0;
  }
}
&#13;
<section class="stop-watch">
1<span>:</span>59
</section>
&#13;
&#13;
&#13;