且构网

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

使用CSS对页面加载产生淡入效果

更新时间:2023-12-05 16:36:40

方法1:

如果您正在寻找自动调用的过渡,则应使用 CSS  3动画.它们也不被支持,但这正是他们的目的.

Method 1:

If you are looking for a self-invoking transition then you should use CSS 3 Animations. They aren't supported either, but this is exactly the kind of thing they were made for.

#test p {
    margin-top: 25px;
    font-size: 21px;
    text-align: center;

    -webkit-animation: fadein 2s; /* Safari, Chrome and Opera > 12.1 */
       -moz-animation: fadein 2s; /* Firefox < 16 */
        -ms-animation: fadein 2s; /* Internet Explorer */
         -o-animation: fadein 2s; /* Opera < 12.1 */
            animation: fadein 2s;
}

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

/* Firefox < 16 */
@-moz-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Internet Explorer */
@-ms-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Opera < 12.1 */
@-o-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

演示

  • http://jsfiddle.net/SO_AMK/VV2ek/
  • Demo

    • http://jsfiddle.net/SO_AMK/VV2ek/
    • 所有现代浏览器和Internet Explorer 10(及更高版本): http://caniuse.com /#feat = css-animation

      All modern browsers and Internet Explorer 10 (and later): http://caniuse.com/#feat=css-animation


      或者,您可以使用jQuery(或普通的JavaScript;请参见第三个代码块)在加载时更改类:

      Alternatively, you can use jQuery (or plain JavaScript; see the third code block) to change the class on load:

$("#test p").addClass("load");​

CSS

#test p {
    opacity: 0;
    font-size: 21px;
    margin-top: 25px;
    text-align: center;

    -webkit-transition: opacity 2s ease-in;
       -moz-transition: opacity 2s ease-in;
        -ms-transition: opacity 2s ease-in;
         -o-transition: opacity 2s ease-in;
            transition: opacity 2s ease-in;
}

#test p.load {
    opacity: 1;
}

普通JavaScript(不在演示中)

document.getElementById("test").children[0].className += " load";

演示

$("#test p").delay(1000).animate({ opacity: 1 }, 700);​

CSS

#test p {
    opacity: 0;
    font-size: 21px;
    margin-top: 25px;
    text-align: center;
}

演示

  • http://jsfiddle.net/SO_AMK/a9dnW/3/
  • Demo

    • http://jsfiddle.net/SO_AMK/a9dnW/3/
    • jQuery 1.x :所有现代浏览器和Internet Explorer 6(及更高版本): http://jquery.com/browser-support/

      jQuery 1.x: All modern browsers and Internet Explorer 6 (and later): http://jquery.com/browser-support/
      jQuery 2.x: All modern browsers and Internet Explorer 9 (and later): http://jquery.com/browser-support/

      此方法最兼容,因为目标浏览器不需要支持CSS 3过渡动画.

      This method is the most cross-compatible as the target browser does not need to support CSS 3 transitions or animations.