[英]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.