或者,如果您不希望在show和hide之间逐渐过渡(例如闪烁的文本光标),您可以使用以下内容:/* 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[i].style.visibility = show;
}
}, time);})()
这个简单的JavaScript实际上非常快,在许多情况下甚至可能是比CSS更好的默认值。值得注意的是,许多DOM调用使JS动画变慢(例如JQuery的$ .animate())。
它还有第二个好处,即如果你.cursor以后添加元素,它们仍将与其他.cursors 完全同时生成动画,因为状态是共享的,据我所知,这对CSS来说是不可能的。