或者,如果您不希望在显示和隐藏之间进行逐步过渡(例如,闪烁的文本光标),则可以使用以下方法:
/* Also use prefixes with @keyframes and animation to support current browsers */
@keyframes blinker {  
  from { visibility: visible }
  to { visibility: hidden }
  /* Alternatively you can do this:  
  0% { visibility: visible; }
  50% { visibility: hidden; }
  100% { visibility: visible; }
  if you don't want to use `alternate` */
}
.cursor {
  animation: blinker steps(1) 500ms infinite alternate;
}
一切1s .cursor都会从visible到hidden。
如果不支持CSS动画(例如在某些Safari版本中),则可以回退到此简单的JS间隔:
(function(){
  var show = 'visible'; // state var toggled by interval
  var time = 500; // milliseconds between each interval
  setInterval(function() {
    // Toggle our visible state on each interval
    show = (show === 'hidden') ? 'visible' : 'hidden';
    // Get the cursor elements
    var cursors = document.getElementsByClassName('cursor');
    // We could do this outside the interval callback,
    // but then it wouldn't be kept in sync with the DOM
    // Loop through the cursor elements and update them to the current state
    for (var i = 0; i < cursors.length; i++) {
      cursors[i].style.visibility = show;
    }
  }, time);
})()
这个简单的JavaScript实际上非常快,在许多情况下甚至比CSS更好。值得注意的是,有很多DOM调用使JS动画变慢(例如JQuery的$ .animate())。
它还具有第二个优点,即如果.cursor以后添加元素,.cursor由于共享状态,它们仍将与其他元素完全同时进行动画处理,据我所知,这对于CSS是不可能的。