我有一个数组,索引号设置为 65 -90(az 键码)。我想遍历我的数组以查看 keypress 事件产生的 keynum 是否与索引号之一匹配,如果匹配,则将屏幕按钮的颜色变为红色,并将 String.fromCharCode 写入元素的 innerHTML .
可以说我的按钮是这个......
<input type="button" id="a" value="A">
这是我的JS代码...
document.onkeypress = keypress;
function keypress() {
var a = document.getElementById("a");
var b = document.getElementById("b");
var c = document.getElementById("c");
var d = document.getElementById("d");
var e = document.getElementById("e");
var f = document.getElementById("f");
var g = document.getElementById("g");
var h = document.getElementById("h");
var i = document.getElementById("i");
var j = document.getElementById("j");
var k = document.getElementById("k");
var l = document.getElementById("l");
var m = document.getElementById("m");
var n = document.getElementById("n");
var o = document.getElementById("o");
var p = document.getElementById("p");
var q = document.getElementById("q");
var r = document.getElementById("r");
var s = document.getElementById("s");
var t = document.getElementById("t");
var u = document.getElementById("u");
var v = document.getElementById("v");
var w = document.getElementById("w");
var x = document.getElementById("x");
var y = document.getElementById("y");
var z = document.getElementById("z");
var buttons = [];
buttons[65] = a;
buttons[66] = b;
buttons[67] = c;
buttons[68] = d;
buttons[69] = e;
buttons[70] = f;
buttons[71] = g;
buttons[72] = h;
buttons[73] = i;
buttons[74] = j;
buttons[75] = k;
buttons[76] = l;
buttons[77] = m;
buttons[78] = n;
buttons[79] = o;
buttons[80] = p;
buttons[81] = q;
buttons[82] = r;
buttons[83] = s;
buttons[84] = t;
buttons[85] = u;
buttons[86] = v;
buttons[87] = w;
buttons[88] = x;
buttons[89] = y;
buttons[90] = z;
var keynum = (window.event) ? event.keyCode: e.which;
var panel = document.getElementById("panel");
var letter = String.fromCharCode(keynum);
for(i = 65; i <= buttons.length; i++)
{
if(buttons[i] == keynum)
{
buttons[i].style.backgroundColor = 'red';
panel.innerHTML += letter;
}
}
}
我怎样才能使当我按下一个按钮时,相应的屏幕按钮变成红色?这是我的 JS Fiddle ... http://jsfiddle.net/AdamMartin121/VXYFC/14/