如何为克隆元素设置动画?

时间:2016-07-12 11:24:09

标签: javascript jquery animation

我想要做的是循环水平文本滑块。 我的尝试 - 当显示文本结束时,克隆此元素移动到右端并再次播放克隆元素的动画 - 但我无法实现这一点,因为由于某种原因,克隆元素不想动画。 / p>

这是仅限Chrome的应用

以下是jsfiddle

CSS

#elm {
  width: 100px;
  height:20px;
  overflow: auto;
  overflow-y: hidden;
  position:absolute;
  top:10px;
  left:10px;
}

#elm::-webkit-scrollbar { width: 0 !important; height: 0 !important; }
#elm .inner-elm {
  position:absolute;
  white-space: nowrap;
}

HTML

<div id="elm">
  <div class="inner-elm"> 11111111 2222222 333333 4444444</div>
</div>

JS

var elm_right = $('#elm').offset().left + $('#elm').outerWidth();

var settings = {
    duration: 5000,
    easing: 'linear',
    step: function() {
      var this_right = $(this).offset().left + $(this).outerWidth();

       // make some clone
      if(!$(this).hasClass('cloned') && ((this_right + 50) < elm_right)) {
        $(this).addClass('cloned');

        var clone = $(this).clone(true);
        clone.addClass('cloned')
          .css('left', $('#elm').width())
          .appendTo('#elm')
          .animate({right:100}, settings);
      }


      // remove parent
      if( (this_right - 20) < $('#elm').offset().left) {
        $(this).remove();
      }

  }
};

var that = $('#elm .inner-elm');
that.animate({right: that.outerWidth()}, settings);

1 个答案:

答案 0 :(得分:0)

您可以将CSS3过渡用于这样的简单动画。 fiddle

var interval = 2000;
var nextTimeout = 200;
var wrapper = $('#elm');
var elem = $('.inner-elm', wrapper);
elem.addClass('move');

setInterval(function(){
  var clone = elem.clone(true);
  elem.remove();
  elem = clone;
  elem.removeClass('move');
  wrapper.append(elem);
  setTimeout(function(){
  	elem.addClass('move');
  }, nextTimeout);
}, interval);
#elm {
  height:20px;
  overflow: auto;
  overflow-y: hidden;
  position:absolute;
  top:10px;
  left:10px;
}

.inner-elm{
    transition: all 2s linear;
    -ms-transform: translate(110%, 0); /* IE 9 */
   	-webkit-transform: translate(110%x, 0); /* Safari */
    transform: translate(110%, 0);
}

.move{
    -ms-transform: translate(-130%, 0); /* IE 9 */
   	-webkit-transform: translate(-130%, 0); /* Safari */
    transform: translate(-130%, 0);
}

#elm::-webkit-scrollbar { width: 0 !important; height: 0 !important; }
#elm .inner-elm {
  position:relative;
  white-space: nowrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="elm">
  <div class="inner-elm">Stackoverflow</div>
</div>