How do I animate an element to swing in CSS3?

拈花ヽ惹草 提交于 2019-11-30 15:23:30

You might want to try using transform: rotate() and like in sven's comment change the prefix to "-moz-" not "-webkit-" because you are using mozilla animations.

Here is an example: http://jsfiddle.net/gVCWE/14/

.box{
    width:50px; height:50px;
    background: yellow;
    border: 1px solid black;
    margin:100px;
    position: relative;
    float: left;
    -moz-animation: 3s ease 0s normal none infinite swing;
    -moz-transform-origin: center top;
    -webkit-animation:swing 3s infinite ease-in-out;
    -webkit-transform-origin:top;
}

@-moz-keyframes swing{
    0%{-moz-transform:rotate(-3deg)}
    50%{-moz-transform:rotate(3deg)}
    100%{-moz-transform:rotate(-3deg)}
}
@-webkit-keyframes swing{
    0%{-webkit-transform:rotate(-3deg)}
    50%{-webkit-transform:rotate(3deg)}
    100%{-webkit-transform:rotate(-3deg)}
}

Also, the reason they have -moz-transform-origin: center top; is so it rotates around the top so using left: -2px to left: 200px will not make sense.

EDIT: new jsfiddle example: http://jsfiddle.net/gVCWE/20/

When I used the above method, It worked fine in all browsers except IE. By using below code, the 'swing' will work in IE10 & IE11. So sad that IE9 couldn't make it ;P

.box{
    width:50px; height:50px;
    background: yellow;
    border: 1px solid black;
    margin:100px;
    position: relative;
    float: left;
    -moz-animation: 3s ease 0s normal none infinite swing;
    -moz-transform-origin: center top;
    -webkit-animation:swing 3s infinite ease-in-out;
    -webkit-transform-origin:top;
    -ms-animation:swing 3s infinite ease-in-out;
    -ms-transform-origin:top;
}

@-moz-keyframes swing{
    0%{-moz-transform:rotate(-3deg)}
    50%{-moz-transform:rotate(3deg)}
    100%{-moz-transform:rotate(-3deg)}
}
@-webkit-keyframes swing{
    0%{-webkit-transform:rotate(-3deg)}
    50%{-webkit-transform:rotate(3deg)}
    100%{-webkit-transform:rotate(-3deg)}
}
@-ms-keyframes swing{
    0%{-ms-transform:rotate(-3deg)}
    50%{-ms-transform:rotate(3deg)}
    100%{-ms-transform:rotate(-3deg)}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!