I want to fill my color selection by Script
. When I want to fill my color menu I use this code:
function FillFontColorMenu() {
FillSelection(GetPossibleColors(), "fontColorMenu"); // Color of the Font
}
function FillBackgroundColorMenu() {
FillSelection(GetPossibleColors(), "backgroundColorMenu"); // Background Color
}
function GetPossibleColors() { // Create an Array of Colors
var possibleColors = [];
possibleColors.push(0x333333); // Add Color x
possibleColors.push(0x666666);
possibleColors.push(0x999999);
return possibleColors; // Return the Colors
}
function FillSelection(possibleValues, elementId) { // Fill the Selection with the Colors
for(var i = 0; i < possibleValues.length; i++) {
var optionElement = "<option value='" + possibleValues[i] + "'>" + possibleValues[i] + "</option>"; // Pass in the Colors
$('#'+elementId).append(optionElement);
}
}
How can I store the colors to the Array
? Do I have to store the values to RGB
codes? Can I use this color Array
and pass the colors in the "FillingMethod"? Is there a way to do this or is my idea crap and will never work?
I tried to create a JsFiddle that shows my problem: Fiddle
You are storing the colors in the Array
as hexadecimal numbers and JavaScript
treats all numbers as double-precision float point numbers . When you insert the color in the option
as a text you need to convert the number to String
. I recommend you to use the toString
method of the Number
object, sending 16
as the base number to get a hexadecimal representation of the number:
FillFontColorMenu(); FillBackgroundColorMenu(); function FillFontColorMenu () { FillSelection(GetPossibleColors(), "fontColorMenu"); } function FillBackgroundColorMenu () { FillSelection(GetPossibleColors(), "backgroundColorMenu"); } function GetPossibleColors () { var possibleColors = []; possibleColors.push(0x333333); // TEST possibleColors.push(0x666666); // TEST possibleColors.push(0x999999); // TEST return possibleColors; } function FillSelection (possibleValues, elementId) { for(var i = 0; i < possibleValues.length; i++) { var optionElement = "<option value='" + possibleValues[i] + "'>#" + possibleValues[i].toString(16) + "</option>"; $('#'+elementId).append(optionElement); } }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="fontColorMenu"></select> <select id="backgroundColorMenu"></select>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.