[英]Change DIV Background Color, Depending on Its Width
我想基于它的CSS属性width
值,使用jQuery动态修改<div>
的背景色。
该用法用于某种形式的彩色编码仪表,该仪表指示设备在特定类别(有5个)中的表现(或不佳),然后有一个“总体”类别,该类别会产生总得分,基于在一点数学上(将所有5加在一起,然后将答案除以5)。
我尝试了两种方法 ,一种基于我所掌握的jQuery知识,另一种根据SO的答案改编而成。 两者都包含在我提供的JSFiddle中,而后者已被注释掉。
以下是每种颜色的颜色和宽度范围:
谢谢!
我建议:
$('.rating-bar').css('background-color', function(){
var percentage = parseInt($(this).data('size'), 10);
if (percentage > 0 && percentage < 25){
return '#a41818'
}
else if (percentage > 24 && percentage < 50) {
return '#87581c';
}
else if (percentage > 49 && percentage < 75) {
return '#997815';
}
else if (percentage > 74 && percentage < 90) {
return '#7ba01c';
}
else if (percentage > 89 && percentage <= 100) {
return '#3a8d24';
}
});
JS小提琴演示 。
存在一些语义问题(使用$(e)
代替$(this)
, ($(document).ready
奇怪地嵌套),并且您使用的逻辑要求每个条的宽度与父条的宽度之比,而不是宽度本身。
试试这个: http : //jsfiddle.net/VFSUN/1/
$(document).ready(function () {
var bar = $('.rating-bar');
bar.css("background-color", "#7ba01c");
var parentWidth = parseInt($('.rating-bar-bg').css("width"));
$('.rating-bar').each(function () {
var e = $(this).css("width");
e = parseInt(e);
ratio = e / parentWidth * 100;
if (ratio <= 24) {
$(this).css("background-color", "#a41818");
} else if (ratio >= 25 && e < 50) {
$(this).css("background-color", "#87581c");
} else if (ratio >= 50 && e < 75) {
$(this).css("background-color", "#997815");
} else if (e >= 75 && e < 91) {
$(this).css("background-color", "#7ba01c");
} else if (ratio >= 91) {
$(this).css("background-color", "#3a8d24");
}
});
});
我建议您通过检查宽度来从错误的角度出发,而实际上您需要根据data-size
属性设置宽度。 然后可以使用此大小设置背景色
$(document).ready(function() {
$('.rating-bar').each(function(){
var $bar=$(this), size=$bar.data('size');
$bar.width(size+'%').css("background-color", getBackground( size))
});
});
function getBackground( e){
var color= "#a41818";/* < 24*/
if (e >= 25 && e < 50) {
color= "#87581c";
} else if (e >= 50 && e < 75) {
color= "#997815";
} else if (e >= 75 && e < 91) {
color= "#7ba01c";
} else if (e >= 91) {
color= "#3a8d24";
}
return color
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.