1

我正在尝试制作进度条。HTML如下:

<div class="progress-bar" style="width:5%"></div>

我想根据它的宽度绘制 DIV 的背景。比如低于100(返回的值以px为单位),我希望它被涂成红色。

我尝试了以下方法:

var currentWidth = $('.progress-bar').width();
if (currentWidth < 100) {
    $('.progress-bar').css('background-color','red');
}

这是 JSFiddle 上的演示。

但它不是画它。

我不习惯使用 javascript 和 jquery,所以我相信这可能是语法错误或我看不到的东西。任何人都可以帮我如何使它工作吗?

提前致谢。

4

4 回答 4

1

你的代码很好。唯一的事情是指定height

<div class="progress-bar" style="width:5%;height:5px"></div>

你的 js 应该看起来很像

$(function () {
    var currentWidth = $('.progress-bar').width();
    console.log(currentWidth);
    if (currentWidth < 100) {
        $('.progress-bar').css('background-color', 'red');
    }
});

小提琴

于 2013-07-26T15:16:45.443 回答
1

Here is a "manual" progress bar that you can increase by clicking a button to see how it changes color and size as it grows. Just remove the button and place with in your loop to do the same thing automatically.

Demo

HTML

<div class="progress-bar"></div>
<input type="button" id="increase" value="Increase" />

CSS

.progress-bar {
    border: 1px solid black;
    width: 5px;
    height: 50px;
}

jQuery

$(document).on("click", "#increase", function () {
    var currentWidth = $('.progress-bar').width();
    currentWidth += 5;
    $('.progress-bar').css('width', currentWidth + 'px');
    if (currentWidth < 100) {
        $('.progress-bar').css('background-color', 'red');
    } else if (currentWidth < 200) {
        $('.progress-bar').css('background-color', 'yellow');
    } else {
        $('.progress-bar').css('background-color', 'green');
    }
});
于 2013-07-26T15:34:56.503 回答
0

您的代码正在运行,您可能需要将代码放入document.ready并在 div 中放入一些文本以查看结果。还要确保你成功地引入了 jQuery。

现场演示

html

<div class="progress-bar" style="width:5%">123</div>

Javascript

$(document).ready(function(){
    var currentWidth = $('.progress-bar').width();
    if (currentWidth < 100) {
        $('.progress-bar').css('background-color','red');
    }
});
于 2013-07-26T15:13:01.123 回答
0

由于您使用的是内联样式,因此您可以使用 div 的样式属性来获取以 % 为单位的宽度

var currentWidth = $('.progress-bar')[0].style.width;
if (parseFloat(currentWidth, 10) < 100) {
    $('.progress-bar').css('background-color','red');
}

对于多个

$('.progress-bar').each(function(){
    var currentWidth = this.style.width;
    if (parseFloat(currentWidth, 10) < 11) {
        $(this).css('background-color','red');
    }
});
于 2013-07-26T15:13:22.433 回答