在css的3D轮子转动的作用

时间:2017-11-13 01:16:39

标签: javascript html css css3 translation

我正在尝试构建一个简单的Web元素,类似于轮播参赛者旋转价格是正确的(sample video)。我的问题是:有没有比我在下面拼凑的更有效的方法来实现这种效果?

我对此功能的第一次尝试基本上减少了包含要旋转的元素 [codepen]的元素的translateY属性:



setInterval(shiftCards, 100)

var translateY = -60,
    cardIdx = 0,
    startCards = 60,
    wrap = document.querySelector('.wrap');

for (var i=0; i<startCards; i++) {
  addCard()
}

function addCard() {
  var div = document.createElement('div');
  div.className = 'card';
  div.style.top = (cardIdx * 12) + 'px';
  wrap.appendChild(div);
  cardIdx++;
}

function shiftCards() {
  wrap.style.transform = 'translateY(' + translateY + 'px)';
  translateY -= 12;
  var cards = wrap.querySelectorAll('.card');
  if (cards.length >= startCards) {
    cards[0].parentNode.removeChild(cards[0]);
    addCard();
  }
}
&#13;
.cards {
  width: 80px;
  height: 200px;
  overflow: hidden;
  background: #aaa;
}

.wrap {
  position: relative;
  transition: transform .25s;
}

.card {
  width: 100%;
  height: 10px;
  margin: 2px 0;
  background: red;
  position: absolute;
  left: 0;
  right: 0;
}
&#13;
<div class='cards'>
   <div class='wrap'>
  </div>
</div>
&#13;
&#13;
&#13;

是否有更有效的方法来实现此功能?我可以创建一个包含n个子元素的元素,实际上只是在Z维度中旋转它们,而不是像我上面所做的那样创建一个人工旋转?任何其他人可以就此问题提供的指导将非常感谢!

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

你可以使用css-animations :(它们可能更有效率)

&#13;
&#13;
/* only alignment */
body, html {
  height: 100%;
  margin: 0;
  padding: 0;
}

.wrapper {
  display:flex;
  justify-content:center;
  align-items:center;
  height: 100%;
}

/* actual spinning */
img {
  animation: spin 5s infinite linear;
  /*
    spin:   the keyframes (=animation) we want to have
    5s:     how long it should take for one iteration
    infinite: how often should it repeat
    linear: the easing between the different key frames You can also try 'ease'
  */
}


@keyframes spin {
    0%   {transform: translateY(-60px);}    /* Starting point */
    100% {transform: translateY(-360px);}  /* end point */
}

@-webkit-keyframes spin {
    0%   {transform: translateY(-60px);}
    100% {transform: translateY(-360px);}
}
&#13;
<div class="wrapper">
  <img src="https://www.placecage.com/300/100" class="spin">
</div>
&#13;
&#13;
&#13;