使用jquery.animate()的CSS旋转跨浏览器

我正在创建跨浏览器兼容的旋转(ie9 +),并且在jsfiddle中有以下代码


$(document).ready(function () { 

    DoRotate(30);

    AnimateRotate(30);

});


function DoRotate(d) {


    $("#MyDiv1").css({

          '-moz-transform':'rotate('+d+'deg)',

          '-webkit-transform':'rotate('+d+'deg)',

          '-o-transform':'rotate('+d+'deg)',

          '-ms-transform':'rotate('+d+'deg)',

          'transform': 'rotate('+d+'deg)'

     });  

}


function AnimateRotate(d) {


        $("#MyDiv2").animate({

          '-moz-transform':'rotate('+d+'deg)',

          '-webkit-transform':'rotate('+d+'deg)',

          '-o-transform':'rotate('+d+'deg)',

          '-ms-transform':'rotate('+d+'deg)',

          'transform':'rotate('+d+'deg)'

     }, 1000); 

}

CSS和HTML非常简单,仅用于演示:


.SomeDiv{

    width:50px;

    height:50px;       

    margin:50px 50px;

    background-color: red;}


<div id="MyDiv1" class="SomeDiv">test</div>

<div id="MyDiv2" class="SomeDiv">test</div>

使用时旋转有效,.css()但使用时无效.animate(); 为什么会这样,有没有办法解决?


谢谢。


绝地无双
浏览 1174回答 3
3回答

繁花不似锦

如果您通过jQuery处理CSS3动画,那么jQuery过渡可能会使您的生活更轻松。EDIT 2014年3月 (因为自从我发表建议以来,我的建议一直在上下投票)让我解释一下为什么我最初暗示上面的插件:就性能而言,更新DOM每个步骤(即$.animate)都不理想。它可以工作,但很可能会比纯CSS3过渡或CSS3动画慢。这主要是因为,如果您指出从头到尾的过渡情况,浏览器将有机会思考。为此,例如,您可以为过渡的每个状态创建一个CSS类,并且仅使用jQuery切换动画状态。通常这很整洁,因为您可以调整动画以及CSS的其余部分,而不必将其与业务逻辑混合在一起:// initial state.eye {&nbsp; &nbsp;-webkit-transform: rotate(45deg);&nbsp; &nbsp;-moz-transform: rotate(45deg);&nbsp; &nbsp;transform: rotate(45deg);&nbsp; &nbsp;// etc.&nbsp; &nbsp;// transition settings&nbsp; &nbsp;-webkit-transition: -webkit-transform 1s linear 0.2s;&nbsp; &nbsp;-moz-transition: -moz-transform 1s linear 0.2s;&nbsp; &nbsp;transition: transform 1s linear 0.2s;&nbsp; &nbsp;// etc.}// open state&nbsp; &nbsp;&nbsp;.eye.open {&nbsp; &nbsp;transform: rotate(90deg);}// Javascript$('.eye').on('click', function () { $(this).addClass('open'); });如果任何变换参数是动态的,那么您当然可以改用style属性:$('.eye').on('click', function () {&nbsp;&nbsp; &nbsp; $(this).css({&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; -webkit-transition: '-webkit-transform 1s ease-in',&nbsp; &nbsp; &nbsp; &nbsp; -moz-transition: '-moz-transform 1s ease-in',&nbsp; &nbsp; &nbsp; &nbsp; // ...&nbsp; &nbsp; &nbsp; &nbsp; // note that jQuery will vendor prefix the transform property automatically&nbsp; &nbsp; &nbsp; &nbsp; transform: 'rotate(' + (Math.random()*45+45).toFixed(3) + 'deg)'&nbsp; &nbsp; });&nbsp;});有关MDN上CSS3过渡的更多详细信息。但是,还需要记住其他一些事项,如果您具有复杂的动画,链接等,所有这些都会变得有些棘手,而jQuery Transit只是在幕后做了所有棘手的工作:$('.eye').transit({ rotate: '90deg'}); // easy huh ?
打开App,查看更多内容
随时随地看视频慕课网APP