CSS进度条,平滑调整

时间:2017-12-01 20:06:06

标签: css css-animations

我正在写一个倒计时栏,有时候需要从js调整。直接设置currentTime太刺耳了 - 我想转换到新值。我有一个工作原型,滥用playbackRate快速跳转到新的位置,但它很hacky并且不允许像放松一样更漂亮的动作。有没有更好的方法来达到类似的效果?

https://jsfiddle.net/isaacly/byac2gqe



var totalClockMs = 6000;  // set this to "total" clock time.
var transitionMs = 100;

var anim = document.getElementsByClassName("progress")[0].animate(
  [
    { transform: 'scaleX(1)' },
    { transform: 'scaleX(0)' }
  ], {
    duration: totalClockMs,
    fill: "both"
  }
);
anim.pause();

var i = 1;
var desired;
var callback;
var callbackFn;
$('#change').click(function() {
  if (i++ % 2 === 0) {
    anim.pause();
    var current = anim.currentTime;
    // Example of setting bar after move finishes, in this case adding 500ms.
    anim.playbackRate = -500 / transitionMs;
    anim.play();
    callbackFn = () => {
      //console.log(current - 500 - anim.currentTime);
      callback = undefined;
      anim.pause();
      anim.currentTime = current - 500;
      anim.playbackRate = 1;
    };
    callback = setTimeout(callbackFn, transitionMs);
  } else {
    if (callback !== undefined) {
      clearTimeout(callback);
      callbackFn();
    }
    anim.play();
  }
});

.progress-bar {
  height: 10px;
  background-color: #e5e9eb;
}

.progress {
  background-color: #90ee90;
  height: 100%;
  transform-origin: left;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="progress-bar">
  <div class="progress">
  </div>
</div>
<br />
<button id="change">Pause/Play</button>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

也许您可以尝试使用CSS transition和setInterval函数。我的想法是当你按下按钮时停止动画,这样你就可以避免跳跃。

这是一个简单的例子:

<强>更新

您还可以通过增加/减少CSS中的step值或转换属性的时间来控制动画的速度。

var step=5;
var tran=0.3;
var run=0;

function speed_control() {
  step+=10;
  $('.progress').css('transition',(tran++)+'s');
}

$('#change').click(function() {
   run=(run+1)%2;
   speed_control();
});

setInterval(function(){ 
  if(run) {
    $('.progress').css('right','+='+step+'px');
  }
}, 300);
.progress-bar {
  height: 10px;
  background-color: #e5e9eb;
  position:relative;
}

.progress {
  position:absolute;
  top:0;
  right:0;
  left:0;
  bottom:0;
  background-color: #90ee90;
  transition:0.3s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="progress-bar">
  <div class="progress">
  </div>
</div>
<br />
<button id="change">Pause/Play</button>