У меня есть задача установить цвет фона для каждого div с немного отличающимся цветом рядом. Div генерирует динамически. Так как я могу установить цвет фона с этим div?
Например, у меня есть начальный цвет #fdecbb
Мне нужен соответствующий цвет выше. Может быть, мне нужно 10 или меньше.
var x =parseInt($('#colorNo').val());
var y = $('#colorCode').val();
for(var i =1;i<x;i++)
{
$('#hai').append($('<div class="colorcode">'+i+'</div>'));
}
CSS
.colorcode
{
background-color:#86173e;
width:100px;
height:100px;
margin-top:10px;
}
HTML-код
<div id="hai"><input type="text" value="5" id="colorNo"/><input type="text" value="#fdecbb" id="colorCode"/></div>
Демо: скрипка
Найдите ближайший/ближайший цвет HEX небольшого набора цветов
JavaScript
$(document).ready(function() {
function getSimilarColors (color) {
var base_colors=["660000","990000","cc0000","cc3333","ea4c88","993399","663399","333399","0066cc","0099cc","66cccc","77cc33","669900","336600","666600","999900","cccc33","ffff00","ffcc33","ff9900","ff6600","cc6633","996633","663300","000000","999999","cccccc","ffffff"];
//Convert to RGB, then R, G, B
var color_rgb = hex2rgb(color);
var color_r = color_rgb.split(',')[0];
var color_g = color_rgb.split(',')[1];
var color_b = color_rgb.split(',')[2];
//Create an emtyp array for the difference betwwen the colors
var differenceArray=[];
//Function to find the smallest value in an array
Array.min = function( array ){
return Math.min.apply( Math, array );
};
//Convert the HEX color in the array to RGB colors, split them up to R-G-B, then find out the difference between the "color" and the colors in the array
$.each(base_colors, function(index, value) {
var base_color_rgb = hex2rgb(value);
var base_colors_r = base_color_rgb.split(',')[0];
var base_colors_g = base_color_rgb.split(',')[1];
var base_colors_b = base_color_rgb.split(',')[2];
//Add the difference to the differenceArray
differenceArray.push(Math.sqrt((color_r-base_colors_r)*(color_r-base_colors_r)+(color_g-base_colors_g)*(color_g-base_colors_g)+(color_b-base_colors_b)*(color_b-base_colors_b)));
});
//Get the lowest number from the differenceArray
var lowest = Array.min(differenceArray);
//Get the index for that lowest number
var index = differenceArray.indexOf(lowest);
//Function to convert HEX to RGB
function hex2rgb( colour ) {
var r,g,b;
if ( colour.charAt(0) == '#' ) {
colour = colour.substr(1);
}
r = colour.charAt(0) + colour.charAt(1);
g = colour.charAt(2) + colour.charAt(3);
b = colour.charAt(4) + colour.charAt(5);
r = parseInt( r,16 );
g = parseInt( g,16 );
b = parseInt( b ,16);
return r+','+g+','+b;
}
//Return the HEX code
return base_colors[index];
}
//Just for the demo
$('button').click(function(){
$('.base_color').css('backgroundColor',$('input').val());
$('.nearest_color').css('backgroundColor','#'+getSimilarColors($('input').val()));
return false;
});
});
HTML-код
Получите самый близкий цвет
<p>Base color:</p>
<div class="base_color"></div>
<p>Closest color:</p>
<div class="nearest_color"></div>
CSS
div {
width:50px;
height:50px;
margin:0 0 0 20px;
}
p {
margin:20px;
}
Я попробовал что-то вроде этого:
Из кода rgb я случайным образом выбираю значения R, G или B, и я произвольно добавляю или вычитаю значение (здесь определяется в переменной шага, так что вы можете изменить его так, как вы хотите).
$(function(){
var step = 10;
$('#new').on('click',function(){
$lastDiv = $('#wrapper > div:last');
nearColor = $lastDiv.css('backgroundColor');
nearColor = nearColor.replace('rgb(','').replace(')','').split(', ');
rgb = Math.floor(Math.random() * (3));
plusminus = Math.floor(Math.random() * (2)) + 1;
colorToChange = nearColor[rgb];
if(1 === plusminus){
colorToChange = (255 == colorToChange) ? 255-step : Math.min(parseInt(colorToChange)+step,255);
}
else {
colorToChange = (0 == colorToChange) ? step :Math.max(parseInt(colorToChange)- step,0);
}
nearColor[rgb] = colorToChange;
$lastDiv.after('<div style="background:rgb('+nearColor.join()+')" ></div>');
});
});
Вы можете проверить скрипку: здесь