出于有趣的目的,我想使用 JavaScript 创建一个 100x100 html 表格,并使用 onmouseover
来更改颜色。这就像一种简单的绘画方式,但是当我将 onmouseover
更改为 changeColor
函数时,参数是 ClientX
和 ClientY
位置而不是 html 元素。
function createTabel(){
var div = document.getElementById("paint");
var table = document.createElement("table");
table.style.border = "1px solid black";
for (var i = 0; i < 100; i++){
var row = document.createElement("tr");
for (var j = 0; j <100; j++){
var cell = document.createElement("td");
cell.onmouseover = changeColor;
cell.style.height = "3px";
cell.style.width = "3px";
cell.style.padding = "0";
cell.style.margin = "0";
row.appendChild(cell);
}
table.appendChild(row);
}
div.appendChild(table);
}
和changeColor函数:
function changeColor(cell){
var color = document.getElementById("color").value;
cell.style.backgroundColor = color;
}
如何在没有 id 的情况下访问导致事件的 html 元素?
最佳答案
尝试事件:
function changeColor(e){
e = e || window.event;
var el = e.srcElement || e.target; //get the current element(cell)
var color = document.getElementById("color").value;
el.style.backgroundColor = color;
}
关于引用 html 元素的 Javascript 函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29917345/