Trigger CSS3 transition on page load

后端 未结 3 819
夕颜
夕颜 2021-02-15 15:45

I am trying to achieve a loading effect on the page load by CSS3 width transition. Here is the demo.

HTML

相关标签:
3条回答
  • 2021-02-15 16:15

    By removing the class from the span and setting it in JavaScript the browser will apply the transition, but this only works on the first .skill-bar. Also .getElementsByClassName will not work in IE8 or below.

    HTML

    <div class="skill-bar"><span></span></div>
    

    JavaScript

    document.getElementsByClassName('skill-bar')[0].getElementsByTagName('span')[0].className = 'w70';
    

    (so just wrap this in <script> element after the HTML or see run function when page is loaded

    Pure JavaScript demo

    You probably want a jQuery (or other framework) solution to ensure cross-browser compatibility but that introduces a dependency on the framework. If you include jQuery already then great. If not you will need to include that library first and then use:

    jQuery

    $(window).load(function(){
        $('.skill-bar span').addClass('w70');
    });
    

    jQuery demo

    Right click on the output frame and select View frame source to see the output code.

    0 讨论(0)
  • 2021-02-15 16:18

    Add the class throught javascript:

    $(".skill-bar span").addClass("w70");
    

    See fiddle here.

    0 讨论(0)
  • 2021-02-15 16:23

    You can achieve the effect without JavaScript and without any compatibility issue using CSS animation:

    <div class="skill-bar">
        <span class="w70"></span>
    </div>
    

    .skill-bar {
        width: 57%;
        float: left;
        height: 11px;
        border-radius: 5px;
        position: relative;
        margin: 6px 0 12px 0;
        border: 2px solid #00edc2;
    }
    .skill-bar span {
        background: #00edc2;
        height: 7px;
        border-radius: 5px;
        display: inline-block;
    }
    .skill-bar span {
        animation: w70 1s ease forwards;
    }
    .skill-bar .w70 {
        width: 70%;
    }
    @keyframes w70 {
        from { width: 0%; }
        to { width: 70%; }
    }
    

    Fiddle for webkit: http://jsfiddle.net/ySj7t/

    0 讨论(0)
提交回复
热议问题