且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

具有延迟和不透明度的 CSS 动画

更新时间:2022-10-19 13:12:33

不要在元素本身上设置初始 opacity,而是在 @keyframes 中设置它:

#element{-webkit-animation:3s 缓动 0s 正常前进 1 淡入;动画:3s 缓动 0s 正常前进 1 淡入;}@关键帧淡入{0% { 不透明度:0;}66% { 不透明度:0;}100% { 不透明度:1;}}@-webkit-keyframes 淡入{0% { 不透明度:0;}66% { 不透明度:0;}100% { 不透明度:1;}}

此技术消除了动画的延迟,使其立即开始运行.然而,直到动画中的 66% 左右,不透明度才会真正改变.因为动画运行了3秒,所以给出了延迟2秒、淡入1秒的效果.

在此处查看工作示例:https://jsfiddle.net/75mhnaLt/

您可能还想考虑对旧浏览器使用条件注释;IE8 和 IE9.

HTML 中的类似内容:

<!--[如果是 IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en-GB"><![endif]--><!--[如果 IE 7]><html class="no-js lt-ie9 lt-ie8 ie-7" lang="en-GB"><![endif]--><!--[如果 IE 8]><html class="no-js lt-ie9 ie-8" lang="en-GB"><![endif]--><!--[if gt IE 8]><!--><html class="no-js" lang="en-GB"><!--<![endif]-->

然后您可以执行以下操作:

.lt-ie9 #element {不透明度:1;}

I am trying to fade in an element after 2 sec using CSS animation. The code works great in new browsers, but in old browsers the element will stay hidden because of "opacity:0".

I want it to be visible in old browsers and I don't want to involve javascript. Can it be solved using CSS? Eg. some how target browsers that doesn't support animation?

CSS:

#element{
animation:1s ease 2s normal forwards 1 fadein;
-webkit-animation:1s ease 2s normal forwards 1 fadein;
opacity:0
}

@keyframes fadein{from{opacity:0}
to{opacity:1}
}

@-webkit-keyframes fadein{from{opacity:0}
to{opacity:1}
}

HTML:

<div id=element>som content</div>

Just don't set the initial opacity on the element itself, set it within the @keyframes:

#element{
    -webkit-animation: 3s ease 0s normal forwards 1 fadein;
    animation: 3s ease 0s normal forwards 1 fadein;
}

@keyframes fadein{
    0% { opacity:0; }
    66% { opacity:0; }
    100% { opacity:1; }
}

@-webkit-keyframes fadein{
    0% { opacity:0; }
    66% { opacity:0; }
    100% { opacity:1; }
}

This technique takes the delay off of the animation, so that it starts running immediately. However, the opacity won't really change until about 66% into the animation. Because the animation runs for 3 seconds, it gives the effect of a delay for 2 seconds and fade in for 1 second.

See working example here: https://jsfiddle.net/75mhnaLt/

You might also want to look at using conditional comments for older browsers; IE8 and IE9.

Something like the following in your HTML:

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en-GB"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8 ie-7" lang="en-GB"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9 ie-8" lang="en-GB"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en-GB"> <!--<![endif]-->

You could then do something like:

.lt-ie9 #element {
    opacity: 1;
}