jQuery: change css color based on inline style width
If I have this html, how would I change the color based on the width?
<div id="progress_bar" class="meter-bg">
<div class="meter" style="width: 67%;">开发者_开发技巧
</div>
</div>
For example, if the width is between 0 and 33%, green. If it's 33%-66% orange. If it's 66%-100% red.
another way to do it that would allow you to have multiple class for numbers:
var p = 74; // your percentage from someplace
var colors = ['one','two','three']; // names of your css classes
var chosen = colors[0];
i = 1;
while(i < colors.length) {
var m = Math.round((i/colors.length) * 100);
if(p > m){
chosen = colors[i];
i++;
continue;
}
break;
}
console.log(chosen) // chosen now contains the array var you want depending on % p
Here would be my solution: http://jsfiddle.net/jKWFz/
var oMeter = $('.meter');
var percent = 100 * (oMeter.width() / $('#progress_bar').width());
if (percent < 33)
{
oMeter.css('background-color', 'green');
}
else if (percent > 33 && percent <= 66)
{
oMeter.css('background-color', 'orange');
}
else
{
oMeter.css('background-color', 'red');
}
Edit: If the content is loaded in AJAX, all you need to do is wrap the above code in a function, and call it when the content been loaded.
For example:
Updated JSFiddle: http://jsfiddle.net/jKWFz/2/
function setupMeter() {
var oMeter = $('.meter');
var percent = 100 * (oMeter.width() / oMeter.closest('.meter-bg').width());
if (percent < 33) {
oMeter.css('background-color', 'green');
}
else if (percent > 33 && percent <= 66) {
oMeter.css('background-color', 'orange');
}
else {
oMeter.css('background-color', 'red');
}
}
// Example when loading from AJAX:
$.get("some_content.html", function(data) {
$('#container').html(data);
setupMeter();
});
精彩评论