着色css形状与不同的颜色

我正在寻找一种解决方案来为一些css形状着色(不要像在这个例子中那样使用svg: http : //bl.ocks.org/widged/4545199 ,但输出结果非常相似)。 我还需要的是将这些形状保存在不同颜色数组的ID中。

在我的例子中,我正在使用带有id的asdfgh的div 。 我想从左边的方块中选择颜色,然后点击它们在右边选择的方块,然后将颜色更改为之前选择的颜色。

我需要一些方法来存储哪个方块被分配给哪种颜色。 之后我就不得不将这些数据传递给php,但我想能够独自完成这项工作。 这个例子在这里 。

来源:

的index.php

    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]; }   

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; } 

等待示例和建议:)

解:

 function paint(color,id) { var currentID = id; document.getElementById(currentID).style.backgroundColor = color; } 

 

我不知道你的问题究竟是什么,但我认为你要问的是当前的颜色要通过PHP,呵呵?

  function getCurrentColor() { var color = document.getElementById("box").style.backgroundColor; // you can now use AJAX or a form to pass this value to php 

编辑

在评论中更好地解释了OP。 您可以:

  // 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]; } } } 

祝好运!