防止元素在循环CSS3动画中旋转

时间:2012-12-27 16:23:33

标签: jquery html css3

好的,所以这对我来说真的很沮丧,首先如果我的问题框架是错误的,请编辑它(如果你这么认为)......好吧,因为我的屏幕会解释你,但我仍然会就像我的元素应该保持特定的形状,而不是随着动画一起旋转,我错过了一些非常愚蠢的事情?

我想要什么

What I Want

发生了什么

What's Happening

jQuery解决方案受到欢迎(但我会喜欢CSS3解决方案)

  

注意:不要继续使用元素的不透明度,1使用Paint和   另外用Photoshop,What Matter's Square应该像Square一样旋转   形状

HTML

<div><span></span></div>

CSS

@keyframes round_round {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}

div {
    width: 50px;
    height: 50px;
    animation: round_round 3s linear infinite;
    margin: 50px auto 0;
    transform-origin: 50% 150px;
    background-color: #8FC1E0;
}

span {
    display: inline-block;
    margin: 5px;
    height: 5px;
    width: 5px;
    background: #c00000;
}

Demo

2 个答案:

答案 0 :(得分:16)

绝对定位,不要更改transform-origin,请将其保留在50% 50%

然后只需旋转元素,将其转换为半径值,然后取消第一次旋转 - 您可以看到链接变换的工作原理here

@keyframes rot {
  0% { transform: rotate(0deg) translate(150px) rotate(0deg); }
  100% { transform: rotate(360deg) translate(150px) rotate(-360deg); }
}

demo

答案 1 :(得分:2)

我刚刚为那些不想使用CSS 3动画的人编写了一个纯JavaScript实现(例如出于兼容性原因)。

Demo

// requestAnim shim layer by Paul Irish
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       || 
          window.webkitRequestAnimationFrame || 
          window.mozRequestAnimationFrame    || 
          window.oRequestAnimationFrame      || 
          window.msRequestAnimationFrame     || 
          function(/* function */ callback, /* DOMElement */ element) {
            window.setTimeout(callback, 1000 / 60);
          };
})();

function CircleAnimater(elem, radius, speed) {
    this.elem = elem;
    this.radius = radius;
    this.angle = 0;
    this.origX = this.elem.offsetLeft;
    this.origY = this.elem.offsetTop;

    this.shouldStop = false;
    this.lastFrame = 0;
    this.speed = speed;
}

CircleAnimater.prototype.start = function () {
    this.lastFrame = +new Date;
    this.shouldStop = false;
    this.animate();
}

CircleAnimater.prototype.stop = function () {
    this.shouldStop = true;
}

CircleAnimater.prototype.animate = function () {
    var now    = +new Date,
        deltaT = now - this.lastFrame;

    var newY = Math.sin(this.angle) * this.radius;
    var newX = Math.cos(this.angle) * this.radius;

    this.elem.style.left = (this.origX + newX) + "px";
    this.elem.style.top = (this.origY + newY) + "px";
    this.angle += (this.speed * deltaT);

    this.lastFrame = +new Date;

    if (!this.shouldStop) {
        var $this = this;
        requestAnimFrame(function () {
            $this.animate();
        });
    }        
}