jquery: addClass, removeClass: 动画只工作一次:为什么?

yar*_*rek 5 css jquery

当我使用它时:

$("#passwordConfig").removeClass('shake animated').addClass('shake animate');
Run Code Online (Sandbox Code Playgroud)

这仅适用一次。

我需要添加一些 timeOut 以使其运行任意多次!

$("#passwordConfig").removeClass('shake animated');
                    setTimeout(function() {
                        $("#passwordConfig").addClass('shake animated');
                    }, 50);
Run Code Online (Sandbox Code Playgroud)

知道为什么吗?

CSS:

.animated {
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}

@-webkit-keyframes shake {
  0%, 100% {
    -webkit-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
  }

  10%, 30%, 50%, 70%, 90% {
    -webkit-transform: translate3d(-10px, 0, 0);
    transform: translate3d(-10px, 0, 0);
  }

  20%, 40%, 60%, 80% {
    -webkit-transform: translate3d(10px, 0, 0);
    transform: translate3d(10px, 0, 0);
  }
}

@keyframes shake {
  0%, 100% {
    -webkit-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
  }

  10%, 30%, 50%, 70%, 90% {
    -webkit-transform: translate3d(-10px, 0, 0);
    transform: translate3d(-10px, 0, 0);
  }

  20%, 40%, 60%, 80% {
    -webkit-transform: translate3d(10px, 0, 0);
    transform: translate3d(10px, 0, 0);
  }
}

.shake {
  -webkit-animation-name: shake;
  animation-name: shake;
}
Run Code Online (Sandbox Code Playgroud)

Ath*_*ace 4

这是因为removeClass 和addClass 发生得如此之快,以至于不允许DOM 跟上。如果你真的讨厌 setTimeout 你可以这样做:

$("#passwordConfig").removeClass('shake animated').delay(50).queue(
    function (next) {
        $(this).addClass('shake animated');
        next();
    }
);
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/51dwhd2o/

Toggle 类也很好,但似乎它只适用于所有其他的切换调用。

  • 不需要延迟它,只需在切换类之间以某种方式强制 ui 重绘,例如 http://jsfiddle.net/51dwhd2o/1/ 我目前无法在除 chrome 之外的其他浏览器上测试它,但众所周知,webkit 浏览器可以优化 ui 重绘,有时太多了,就像这里的情况一样 (2认同)
  • jq 3.x(以及我可以测试的 1.x)上的 Ya 需要是 `.hide().show(0)` 或我不知道的任何更好的方法来强制 ui 重画 (2认同)