2013-07-26 102 views
1

我正在尝试制作一个进度条。该HTML如下:如何通过元素的宽度更改背景颜色?

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

我要根据它的宽度绘制DIV的背景。 例如,如果它低于100(返回的值是px),我希望它被涂成红色。

我tryed如下:

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

Here is the demo on JSFiddle.

但它不是画吧。

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

在此先感谢。

+0

代码看起来很好,只要它在文档准备好之后或者在DOM中的元素之后,但是究竟是在应该发生,仅在页面载入中,还是在某个事件或...上? – adeneo

+0

你需要设置一个高度。否则它不会显示 –

+0

看起来对我很好:http://jsfiddle.net/HxVNj/你给它一个高度或添加任何内容,所以它显示。你在渲染之前调用它吗? – epascarello

回答

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'); 
    } 
}); 
+0

谢谢,但它仍然无法正常工作。它绘制所有进度条。在这里:http://jsfiddle.net/uSSyx/ – LuAmbros

+1

@LuAmbros我想你错过了在前面的例子中添加jQuery – Praveen

+0

没错,它在这里工作,谢谢! http://jsfiddle.net/uSSyx/6/我不知道如何,但它不能在线工作! Myabe,因为我有很多进度条... – LuAmbros

0

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

Live Demo

的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'); 
    } 
}); 
1

你的代码是正确的。唯一的一点是指定height

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

,你JS应该lilke

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

Fiddle

1

这里是“手动”的进度条,您可以通过点击一个按钮,增加怎么看呢随着它的增长而改变颜色和尺寸。只需删除按钮并放入循环中即可自动执行相同的操作。

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'); 
    } 
});