如何在Bootstrap 3中为进度条设置动画?
我试图动画Bootstrap进度条,但我不知道该怎么做。
我得到了宽度的值,但是console.log(bar_width);
以px
返回宽度但不返回%
,如inline style="width:90%
。
我用代码重新创建了一个bootply: BootStrap Progress Bar
HTML:
jQuery的:
// Skills Progress Bar $(function() { $('.progress-bar').each(function() { var bar_width = $(this).css('width'); // returns the css width value var bar_value = $(this).attr('aria-valuenow'); console.log(bar_width); console.log(bar_value); $(this).animate({ value: bar_width }, { duration: 2000, easing: 'easeOutCirc' }); }); });
我假设您希望将进度从零动画到aria-valuenow
指定的数量。 你快到了!
- 从每个进度条中删除
style
属性,因为它会立即将它们置于最终量。 - 我已将
%
添加到bar_value
以使其被识别为百分比。 没有单位,它将被视为像素值。 - jQuery
animate
函数需要知道要设置动画的css属性。 我已将代码示例中的value
更改为width
以设置width
属性的动画 -
easeOutCirc
缓动函数仅存在于jQuery UI中。 我不确定你是否将它作为Bootply中的资源,但我已将其添加到此处。
// Skills Progress Bar $(function() { $('.progress-bar').each(function() { var bar_value = $(this).attr('aria-valuenow') + '%'; $(this).animate({ width: bar_value }, { duration: 2000, easing: 'easeOutCirc' }); }); });
@import url('//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css'); /* CSS used here will be applied after bootstrap.css */ /* Skills Progess Bar */ section#skills-pgr { padding: 3px 10px 0; } #skills-pgr div.progress { font-weight: bolder; color: #fff; background-color: #f3f3f3; border: 0px none; box-shadow: none; height: 2.5em; } div.progress-bar > span { float: left; position: relative; top: 9px; left: 2%; font-size: 14px; }
在Bootstrap 3中,动画进度条非常容易。 您需要做的就是更改.progress-bar
的宽度,如下所示:
$('.progress-bar').css('width', '80%');
只要需要更新宽度值,只需重复该过程,直到过程栏达到100%。
一个演示
var $progress = $('.progress'); var $progressBar = $('.progress-bar'); var $alert = $('.alert'); setTimeout(function() { $progressBar.css('width', '10%'); setTimeout(function() { $progressBar.css('width', '30%'); setTimeout(function() { $progressBar.css('width', '100%'); setTimeout(function() { $progress.css('display', 'none'); $alert.css('display', 'block'); }, 500); // WAIT 5 milliseconds }, 2000); // WAIT 2 seconds }, 1000); // WAIT 1 seconds }, 1000); // WAIT 1 second
.progress, .alert { margin: 15px; } .alert { display: none; }
Loading completed!
您可以使用setInterval计时器并以某个间隔增加宽度,直到达到最大宽度。
$('.progress-bar').each(function() { var $bar = $(this); var progress = setInterval(function() { var currWidth = parseInt($bar.attr('aria-valuenow')); var maxWidth = parseInt($bar.attr('aria-valuemax')); //update the progress $bar.width(currWidth+'%'); $bar.attr('aria-valuenow',currWidth+10); //clear timer when max is reach if (currWidth >= maxWidth){ clearInterval(progress); } }, 500); });