我想将一个进度条从0%到70%地动态地展示出来,时长为2.5秒。但是下面的代码在延迟2.5秒后立即将宽度更改为70%。我错过了什么吗?
$(".progress-bar").animate({
width: "70%"
}, 2500);
JSFiddle:http://jsfiddle.net/WEYKL/
我想将一个进度条从0%到70%地动态地展示出来,时长为2.5秒。但是下面的代码在延迟2.5秒后立即将宽度更改为70%。我错过了什么吗?
$(".progress-bar").animate({
width: "70%"
}, 2500);
JSFiddle:http://jsfiddle.net/WEYKL/
问题出在默认的Bootstrap过渡效果上,该效果会使width
属性的任何更新都产生动画效果。
如果通过抑制相应的样式来关闭它,它将正常工作,例如:
.progress-bar {
-webkit-transition: none !important;
transition: none !important;
}
因此,通过CSS或jQuery调整过渡效果更有意义。
.progress-bar {
-webkit-transition: width 2.5s ease;
transition: width 2.5s ease;
}
只需要更改宽度的值即可。
$(".progress-bar").css('width', '70%');
如果使用Bootstrap进度条,这很容易实现
只需要在class为“progress-bar”的div中添加属性aria-valuenow="percent_required%"即可,格式如下:
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="57%" aria-valuemin="0" aria-valuemax="57">
接下来,关于脚本:
<script>
$(document).on('ready',function(){
$('.progress .progress-bar').css("width",function() {
return $(this).attr("aria-valuenow") + "%";
})
})
</script>
重新加载,出发!
.progress .progress-bar {
transition: unset;
}
var delay = 500;
$(".progress-bar").each(function(i) {
$(this).delay(delay * i).animate({
width: $(this).attr('aria-valuenow') + '%'
}, delay);
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: delay,
// easing: 'swing',
step: function(now) {
$(this).text(Math.ceil(now) + '%');
}
});
});
.progress {
margin-bottom: 20px;
}
.progress-bar {
width: 0;
}
.bg-purple {
background-color: #825CD6 !important;
}
.progress .progress-bar {
transition: unset;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<div class="container">
<h2>Bootstrap 4 Progress Bars</h2>
<div class="progress border">
<div class="progress-bar progress-bar-striped progress-bar-animated bg-danger" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100">70</div>
</div>
<div class="progress border">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100">50</div>
</div>
<div class="progress border">
<div class="progress-bar progress-bar-striped progress-bar-animated bg-purple" role="progressbar" aria-valuenow="90" aria-valuemin="0" aria-valuemax="100">90</div>
</div>
</div>