简体   繁体   English

Javascript。 使用鼠标悬停事件更改数组中td元素的背景颜色

[英]Javascript. Changing background color of td elements in an array with mouseover event

I'm creating a simple paint program with Javascript with really next to no knowledge prior to starting this task. 在开始此任务之前,我几乎没有知识就使用Javascript创建了一个简单的绘画程序。 I'm really close, I can feel it but I'm missing some vital piece of the puzzle. 我真的很接近,我能感觉到,但是我缺少一些至关重要的难题。 A table is generated and on mouseover, the td elements are supposed to change colour. 将生成一个表,并且将鼠标悬停在其上时,td元素将更改颜色。 I'll be adding buttons to change the colour of the paintbrush(mouse) later but that part will be easy enough. 稍后,我将添加按钮以更改画笔(鼠标)的颜色,但是该部分将非常容易。

function drawTable(){
var body = document.body;
var tbl = document.createElement('table');

tbl.setAttribute("id", "canvas");
tbl.style.width = '800px';
tbl.style.border = '1px solid black';
tbl.style.margin = 'auto';


for (var i = 1; i <= 10; i++){
    var tr = tbl.insertRow();
    for (var k = 1; k <= 10; k++){
        var td = tr.insertCell();
        //td.appendChild(document.createTextNode(''));
        td.style.border = '1px solid black';
        td.style.height = '70px';
        td.style.width = '120px';

    }

}
body.appendChild(tbl);
}
drawTable();
var color = "black";
var tableData = document.getElementsByTagName('td');


for (i = 0; i < tableData.length; i++){
    tableData[i].onmouseover = changeColour("red");
}

function changeColour(x){
    this.style.backgroundColor = x;

}
var tableData = document.getElementsByTagName('td');
for (i = 0; i < tableData.length; i++){
    tableData[i].onmouseover = changeColour("red");
}

function changeColour(x){
    return function(){
    this.style.backgroundColor = x;
    }    
}

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

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