猿问

如何使用CSS 3制作闪烁/闪烁文本?

目前,我有这个代码:

@-webkit-keyframes blinker {
  from { opacity: 1.0; }
  to { opacity: 0.0; }}.waitingForConnection {
  -webkit-animation-name: blinker;
  -webkit-animation-iteration-count: infinite;
  -webkit-animation-timing-function: cubic-bezier(.5, 0, 1, 1);
  -webkit-animation-duration: 1.7s;}

它闪烁,但它只在“一个方向”闪烁。我的意思是,它只会淡出,然后它会显示opacity: 1.0出来,然后再次淡出,再次出现,等等......我希望它淡出,然后再次从这个淡入淡出“提升” opacity: 1.0。那可能吗?


郎朗坤
浏览 575回答 3
3回答

函数式编程

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