简体   繁体   English

如何将选定的颜色应用于选定的单元格

[英]How to apply selected color to selected cell

Sir, There is one table with different colors. 主席先生,有一张桌子有不同的颜色。 Under that second table suppose with 3 columns,3rows. 在第二张表下假设有3列3行。

After clicking on the color i will click any cell in the below table.that color have to apply for that particular cell. 单击颜色后,我将单击下表中的任何单元格。该颜色必须适用于该特定单元格。 It is like paint bucket. 就像油漆桶。 Can u tell me how to do this? 你能告诉我该怎么做吗?

CSS: CSS:

td {
    border:1px solid grey;
    width:40px;
    height:40px;
    cursor:hand;
    cursor:pointer;
}

HTML: HTML:

<table id='colors'><caption>Color source</caption><tbody></tbody></table>
<br>
<table id='3x3'>
    <caption>Target</caption>
    <tr><td/><td/><td/></tr>
    <tr><td/><td/><td/></tr>
    <tr><td/><td/><td/></tr>
</table>

SCRIPT: 脚本:

function randColor() {
    var str=Math.round(Math.random()*16777215).toString(16);
    return "#000000".substr(0,7-str.length)+str;
}


var tableColors,table3x3;
var selectedColor=null;
window.onload=function() {
    tableColors=document.getElementById('colors');
    table3x3=document.getElementById('3x3');
    // generating colors table
    for(var r=0;r<5;r++) {
        var tr=tableColors.tBodies[0].appendChild(document.createElement('tr'));
        for(var c=0;c<8;c++) {
            var td=tr.appendChild(document.createElement('td'));
            td.style.backgroundColor=randColor();
        }
    }
    selectedColor=tableColors.rows[0].cells[0].style.backgroundColor;
    // registering event handlers
    if(window.addEventListener) {
        tableColors.addEventListener('mousedown',selectColor,false);
        table3x3.addEventListener('mousedown',applyColor,false);
    }
    else if(window.attachEvent) {
        tableColors.attachEvent('mousedown',selectColor);
        table3x3.attachEvent('mousedown',applyColor);
    }
}

function selectColor(ev) {
    var src=(ev=ev||event).target||ev.srcElement;
    while(src!==tableColors&&
          (!src.tagName||src.tagName.toUpperCase()!=='TD'))
        src=src.parentNode;
    if(src.tagName.toUpperCase()==='TD')selectedColor=src.style.backgroundColor;
}

function applyColor(ev) {
    var src=(ev=ev||event).target||ev.srcElement;
    while(src!==table3x3&&
          (!src.tagName||src.tagName.toUpperCase()!=='TD'))
        src=src.parentNode;
    if(src.tagName.toUpperCase()==='TD')src.style.backgroundColor=selectedColor;
}

http://jsfiddle.net/cUHn7/ http://jsfiddle.net/cUHn7/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM