CSS3 - add class to fire an animation and remove class on completion

人走茶凉 提交于 2019-12-12 12:02:35

问题


I have a div and when I click it jquery adds a class which starts an animation running. When the animation stops (after 3 seconds) I want the class to be removed, so that when the div is clicked on again the animation will start over.

This is only testing and only Chrome browser at the moment.

Here is my CSS3:

.spin360
{
    -webkit-animation-name: spin;
    -webkit-animation-duration: 3s;
    -webkit-animation-iteration-count: 1;
    -webkit-animation-timing-function: ease;
    -webkit-animation-fill-mode: forwards;
}

@-webkit-keyframes spin 
{
    0% { -webkit-transform: rotateX(0); }
    100%   { -webkit-transform: rotateX(-360deg); }
}

Here is my script:

<script type="text/javascript">
    $(document).ready(function () {
        $('#spinButton').click(function () {
            $('#shape').addClass('spin360');
        });
    });
</script>

Here is what I've tried:

<script type="text/javascript">
    $(document).ready(function () {
        $('#spinButton').click(function () {
            $('#shape').addClass('spin360').on('webkitAnimationEnd', function () {
                $('#shape').removeClass('spin360');
            });
        });
    });
</script>

And

<script type="text/javascript">
    $(document).ready(function () {
        $('#spinButton').click(function () {
            $('#shape').addClass('spin360');
        });

        $('#spinButton').addEventListener('webkitAnimationEnd', function (e) {
            $('#shape').removeClass('spin360');
        });
    });
</script>

In all cases - my animation runs on the first click, but not subsequent clicks.


回答1:


You can do it in a cross browser way as well:

$('#spinButton').bind('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd', function (e) {
    $('#shape').removeClass('spin360');
});



回答2:


I was using an older version of jquery.

I updated to 1.8.0 and it works.




回答3:


// works fine however you did leave our standard declaration //so your code would only work on Chrome, Safari, Opera

/* Chrome, Safari, Opera */
@-webkit-keyframes spin { 0% { -webkit-transform: rotateX(0); } 100% { -webkit-transform: rotateX(-360deg); } }

/* Standard syntax */
@keyframes spin { 0% { -webkit-transform: rotateX(0); } 100% { -webkit-transform: rotateX(-360deg); } }



来源:https://stackoverflow.com/questions/11784831/css3-add-class-to-fire-an-animation-and-remove-class-on-completion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!