CSS translateX没有动画效果

时间:2018-02-17 17:30:22

标签: css

我正在尝试将css变换动画添加到某些元素中。我使用以下内容:

#carousel>.items>div {
  transform: translateX(0px);
  animation: transform 1s ease-in-out;
}

但是,当我使用它时,它会立即移动到我告诉它的位置,并且没有动画到该位置。

这是一个示例用法,我实际上并没有在我的源代码中使用jQuery。

运行代码时,单击红色框。它应该有动画,但它没有。



$('.items').on('click', e => {
  $(e.currentTarget).find('div').css('transform', 'translateX(-100px)')
})

#carousel {
  height: 25vh;
  width: 25vw;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  margin: auto;
}

#carousel>.items {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  height: inherit;
  width: inherit;
  overflow: hidden;
  flex: 1;
}

#carousel>.items>div {
  flex-direction: row;
  min-width: 100%;
  height: inherit;
  color: #ffffff;
  transform: translateX(0px);
  animation: transform 1s ease-in-out;
}

#carousel>.items>div:nth-child(1) {
  background-color: #ff0000;
}

#carousel>.items>div:nth-child(2) {
  background-color: #00ff00;
}

#carousel>.items>div:nth-child(3) {
  background-color: #0000ff;
}

#carousel>.items>div:nth-child(4) {
  background-color: #ffff00;
}

#carousel>.items>div:nth-child(5) {
  background-color: #00ffff;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="carousel">
  <div class="items">
    <div>
      <h1>Hello</h1>
    </div>
    <div>
      <h1>World!</h1>
    </div>
    <div>
      <h1>How</h1>
    </div>
    <div>
      <h1>Are</h1>
    </div>
    <div>
      <h1>You</h1>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

应该是transition而不是animation

$('.items').on('click', e => {
  $(e.currentTarget).find('div').css('transform', 'translateX(-100px)')
})
#carousel {
  height: 25vh;
  width: 25vw;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  margin: auto;
}

#carousel>.items {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  height: inherit;
  width: inherit;
  overflow: hidden;
  flex: 1;
}

#carousel>.items>div {
  flex-direction: row;
  min-width: 100%;
  height: inherit;
  color: #ffffff;
  transform: translateX(0px);
  transition: transform 1s ease-in-out;
}

#carousel>.items>div:nth-child(1) {
  background-color: #ff0000;
}

#carousel>.items>div:nth-child(2) {
  background-color: #00ff00;
}

#carousel>.items>div:nth-child(3) {
  background-color: #0000ff;
}

#carousel>.items>div:nth-child(4) {
  background-color: #ffff00;
}

#carousel>.items>div:nth-child(5) {
  background-color: #00ffff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="carousel">
  <div class="items">
    <div>
      <h1>Hello</h1>
    </div>
    <div>
      <h1>World!</h1>
    </div>
    <div>
      <h1>How</h1>
    </div>
    <div>
      <h1>Are</h1>
    </div>
    <div>
      <h1>You</h1>
    </div>
  </div>
</div>