0

我正在尝试实现一个滑动进度条。我希望进度逐渐增加。

我尝试:

HTML

<div id="progressKeeper">
<div id="progress"></div>
</div>

CSS

#progressKeeper {
    width: 800px;
    height: 25px;
    border: 3px double #003366;
    margin: 0px 10px;
    padding: 3px;
}

JavaScript

var el = $('#progress');
var steppedIncreaseAmount = ($('#progressKeeper').width()) / 100;
for (var i = 0; i < 100; i++) {
    el.width(el.width() + steppedIncreaseAmount+ 'px');
}

看到这个jsfiddle

但它只是突然增加。我想要一个平滑的效果,就像一个淡入淡出。

4

5 回答 5

3

您需要在这些值的更新之间设置某种延迟。但是,因为您似乎使用的是 jQuery,所以您可以轻松地执行以下操作:

$(document).ready(function() {
    var el = $('#progress');
    el.animate({
        width: "100%"
    }, 1800);
});​

http://jsfiddle.net/VbVBP/2/

另一种方法,如果你真的想保持现在的设置,只需setTimeout在你的 for 循环中添加一个计数器,如下所示:

var el = $('#progress');
var steppedIncreaseAmount = ($('#progressKeeper').width()) / 100; 
for (var i = 0; i < 100; i++) {
    setTimeout(function(){
        el.width(el.width() + steppedIncreaseAmount+ 'px');
    }, 1+i*20);
}​

http://jsfiddle.net/VbVBP/3/

于 2012-12-27T18:21:25.127 回答
2

一个简单的 for 循环更新值的速度快于你的眼睛可以赶上......

您可以使用计时器功能,例如setInterval基本 JS 动画。这将像:

var increase = setInterval(function(){

    el.width(el.width() + steppedIncreaseAmount+ 'px');

}, 50); //50 is the interval in ms, i.e the function inside the interval gets called 20 times per second

完成动画后(进度为 100%),您应该取消间隔:

clearInterval(increase);

在 setInterval 上查看工作小提琴MDN 文档

如果您想深入了解 JavaScript 动画领域,您可能还想了解requestAnimationFrame

于 2012-12-27T18:21:45.687 回答
1

尝试使用动画:

el.animate({ width: "+=" + steppedIncreaseAmount }, 500);
于 2012-12-27T18:24:13.730 回答
0

哦,不要为此使用javascript。你可以只用 CSS3 动画来做到这一点。

@-webkit-keyframes progress { 
    from { }
    to { width: 100% }
}

和进度条:

-webkit-animation: progress 2s 1 forwards;
-moz-animation: progress 2s 1 forwards;
-ms-animation: progress 2s 1 forwards;
animation: progress 2s 1 forwards;

工作示例:http: //jsfiddle.net/VbVBP/4/

于 2012-12-27T18:41:28.363 回答
0

我设置了一个演示,说明我能想出什么。http://jsfiddle.net/VbVBP/5/ 我将更新时间设置为 300 毫秒,更新动画的速度也设置为 300,因此它不断动画。

您将使用操作完成的任何百分比,而不是使用随机值。

<div id="progressKeeper">
<div id="progress"></div>
</div>​

var randomPercentInt = 0;

function percentComplete(percent) {
    var el = $('#progress');
    el.animate({
        width: percent
    }, 300);
}

$(document).ready(function() {
    percentComplete('0%');
});

function randomPercent() {
    var randomNumber = Math.floor(Math.random() * 10);
    randomPercentInt += randomNumber;
    console.log(randomPercentInt);
    if(randomPercentInt>100)
    {
        randomPercentInt = 100;
        clearInterval(clearme);
    }
    percentString = randomPercentInt.toString() + '%';
    percentComplete(percentString);
}
clearme = setInterval(randomPercent, 300);​
于 2012-12-27T18:55:51.547 回答