问题
I'm looking for a solution to color some css shapes (don't really want to use svg as in this example: http://bl.ocks.org/widged/4545199 , but the output would be pretty similar). What I need moreover is having these shapes saved with their ID's in different color arrays.
In my example I'm using div's with id's asd and fgh. I want to choose the color from the square on the left and color the squares I select on the right with clicking on them so the color would change to the one previously selected.
And I need some method of storing which of the square is assigned to which colour. Later then I would have to pass this data to php, but I will be able to manage to do this alone, I guess. The example is here.
And the sources:
index.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script>
var colors = ["white","red","blue","green","yellow","purple"];
var index = 0;
function button_click() {
index = (index + 1) % colors.length;
document.getElementById("box").style.backgroundColor = colors[index];
}
</script>
<body>
<div id="box" onclick="button_click();"></div>
<div class="t1" id="asd"></div>
<div class="t1" id="fgh"></div>
</body>
</html>
mystyle.css
div#box
{
width:20px;
height:20px;
background-color: white;
border-color: black;
border-style: solid;
border-width: 1px 1px 1px 1px;
float: left;
}
.t1
{
width:50px;
height:50px;
background-color: black;
border-color: white;
border-style: solid;
border-width: 1px 1px 1px 1px;
float: right;
}
Waiting for both examples and suggestions :)
Solution:
function paint(color,id) {
var currentID = id;
document.getElementById(currentID).style.backgroundColor = color;
}
and
<div class="t1" id="asd" onclick="paint(colors[index],this.id);"></div>
回答1:
I don't know what is exactly your question, but I think that you are asking about to get the current color to pass through PHP, huh?
function getCurrentColor() {
var color = document.getElementById("box").style.backgroundColor;
// you can now use AJAX or a form to pass this value to php
EDIT
OP was explained better in comment. You can:
// add style to 3 boxes
function button_click() {
index = (index + 1) % colors.length;
document.getElementById("box").style.backgroundColor = colors[index];
document.getElementById("asd").style.backgroundColor = colors[index];
document.getElementById("fgh").style.backgroundColor = colors[index];
}
// returns the current color of #box
function getColor() {
return document.getElementById("box").style.backgroundColor;
}
function whichIsColor(color) {
// select all elements
var els = document.getElementsByTagName("div");
//iterate through them
for(var i in els) {
// if matches the color passed in argument:
if(els[i].style.backgroundColor === color) {
return els[i];
}
}
}
Good luck!
来源:https://stackoverflow.com/questions/31675511/coloring-css-shapes-with-different-colors