如果用户投票,我试图填写一个栏,如果价值"得分"在我的json文件中是10然后jQuery必须将10%的红色添加到栏中:
JQuery代码:
$(document).ready( function(){
$.getJSON( "js/json/sidekicks.json", function(obj){
$.each(obj.Sidekicks, function(key, value){
$('div#sidekicks' + value.Id + 'span.red-line-fill').text(value.Score);
});
});
});
HTML:
<div id="sidekicks" class="side-kick-holder">
<ul>
<li>
<a href="" >
<div id="1098" class="hit super-box shuv-down-10" >
<h4>Rose Tyler <span class="thin">(Dr Who)</span>
<div class="circle"><img id="red-tick" class="change-img" data-alt-src="img/circle-hover.png" src="img/circle-grey.png" alt="circle"></div>
</h4>
<div class="line-grey"><span class="red_line_fill"></span></div>
</div>
</a>
</li>
</ul>
</div>
这是我的json文件,包含所有值:
{
"Sidekicks": [
{
"Id": 1098, // this will be the sidekick "Rose Tyler(Dr Who)" but this name can change at any time;
"Score": 20
},
{
"Id": 1099, // this will be the sidekick "Dr Watson" but this name can change at any time;
"Score": 10
},
{
"Id": 1100, // this will be the sidekick "Chewbacca" but this name can change at any time;
"Score": 30
},
{
"Id": 1101, // this will be the sidekick "Robin" but this name can change at any time;
"Score": 10
},
{
"Id": 1102, // this will be the sidekick "Donkey (from Shrek)" but this name can change at any time;
"Score": 20
},
{
"Id": 1103, // this will be the sidekick "Gromit" but this name can change at any time;
"Score": 10
}
]
}
答案 0 :(得分:0)
使用
var color = (score / 100) * 255;
$('#example-selector').css('background-color', 'rgb(color + ', 0, 0)');
这应该是这样的:高分(100,我猜),将是完整的RED,#FF0000。 而最低分(0,我推测),将是完整的黑色。
只需在您的代码中实现此功能。
最佳答案:
$(document).ready( function(){
var MAX_WIDTH = 100; // Define max bar width in Pixels here
$.getJSON( "js/json/sidekicks.json", function(obj){
$.each(obj.Sidekicks, function(key, value){
var color = 'rgb(' + ((value.Score / 100) * 255) + ', 0, 0';
var width = (value.Score / 100) * MAX_WIDTH;
$('div#' + value.Id).find('.red_line_fill').text(value.Score).css("background-color", color).width(width);
});
});
});
此代码的行为是,对于每个条形,它将按比例更改颜色(其中0表示黑色,100表示纯红色)和宽度(其中0表示0像素,100表示MAX_WIDTH值,以像素为单位)
请验证任何javascript错误,因为这里是深夜,也许我错过了一些东西。