jquery setInterval函数中SetValue和bootstrap进度条宽度不匹配

SetValue and bootstrap progress-bar width not matching in jquery setInterval function

本文关键字:不匹配 bootstrap setInterval 函数 SetValue jquery      更新时间:2023-09-26

设置进度条宽度的值很好,但是当我在控制台上检查它们或查看页面上的结果时,它们显然是不正确的。由于某些原因,只有当复选框的选项为1而不是2时才会发生这种情况。

var timeInterval;
// For procedure parameter
var choice;
if (document.getElementById('myonoffswitch').checked == false) {
    choice = 1;
    timeInterval = 300;
} else {
    choice = 2;
    timeInterval = 13400;
};
var $bar = $('.progress-bar');
var $barWidth = $('#pBar');
var barIntervalLength = 0;
var curBarWidth = 0;
var setWidth = 0;
var percentDisplay = 0;
$bar.width(0);
var progress = setInterval(function () {
barIntervalLength = $barWidth.width() / 20;
curBarWidth = $bar.width();
setWidth = barIntervalLength + curBarWidth;
    percentDisplay = percentDisplay + 5;
if (percentDisplay > 100) {
    clearInterval(progress);
    $('.progress').removeClass('active');
} else {
    $bar.width(setWidth);
    $bar.text(percentDisplay + "%");
    console.log("set: " + setWidth);
    console.log("barWidth: " + $barWidth.width());
    console.log("barIntervalLength: " + barIntervalLength);
    console.log("bar.width: " + $bar.width());
    };
}, timeInterval);

下面是控制台的结果:

set: 27.9
barWidth: 558
barIntervalLength: 27.9
bar.width: 0
set: 46.9
barWidth: 558
barIntervalLength: 27.9
bar.width: 19
set: 67.9
barWidth: 558
barIntervalLength: 27.9
bar.width: 40

第二栏。Width:应该是27.9,3rd应该是55.8(或者非常接近这些数字)。

如果复选框被选中(选项2),这些结果是正确的:

set: 27.9
barWidth: 558
barIntervalLength: 27.9
bar.width: 0
set: 55.9
barWidth: 558
barIntervalLength: 27.9
bar.width: 28
set: 83.9
barWidth: 558
barIntervalLength: 27.9
bar.width: 56
set: 111.9

我只是用头撞桌子想弄明白这个问题。

希望有人能告诉我这是怎么回事。

引导进度条使用css过渡来加宽/缩短。jquery的width()函数返回元素的实际宽度。当choice=1时,您的间隔为300ms,这比转换时间要短得多。因此,您正在检索的宽度介于初始宽度和您设置的宽度之间。

下面是正在发生的事情的演示:

$(function() {
  setInterval(function() {
    $('.progress').width(1000);
  }, 1000);
  setInterval(function() {
    console.log($('.progress').width());
  }, 100);
});
.progress {
  width: 0;
  height: 40px;
  background: blue;
  transition: linear 10s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="progress"></div>

在js中保存你想要元素的实际宽度。比如:

var $bar = $('.progress-bar');
var $barWidth = $('#pBar');
var barIntervalLength = 0;
var curBarWidth = 0;
var percentDisplay = 0;
$bar.width(curBarWidth);
var progress = setInterval(function () {
barIntervalLength = $barWidth.width() / 20;
curBarWidth += barIntervalLength ;
    percentDisplay = percentDisplay + 5;
if (percentDisplay > 100) {
    clearInterval(progress);
    $('.progress').removeClass('active');
} else {
    $bar.width(curBarWidth);
    $bar.text(percentDisplay + "%");
    console.log("barWidth: " + $barWidth.width());
    console.log("barIntervalLength: " + barIntervalLength);
    console.log("bar.width: " + $bar.width());
    };
}, timeInterval);