/*JS键盘
*实现大小写切换,使用时需指定页面上出现的位置,及接收输入的控件名称.
*边框文字样式需在css中指定.
*div1:出现的位置控件名称
*div2:接收输入的控件名称
*/
var shift=false;//shift开关
var caps=false;//caps开关
var nowchar,nownum;
var i;
var upcolor="#cfffff";//caps,shift按下抬起颜色
var downcolor="#5fffff";
function createKeyBoard(div1,div2){
//为了赋值和取值方便,定义数组
var valuechar1=new Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
var valuechar2=new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
var valuenum1=new Array("1","2","3","4","5","6","7","8","9","0");
var valuenum2=new Array("!","@","#","$","%","^","&","*","(",")");
//创建表格
var otable=document.createElement("table");
otable.style.border="1px solid green";
otable.setAttribute("width","340");
otable.setAttribute("height", "60");
var otbody=document.createElement("tbody");
otable.appendChild(otbody);
//加入第一行
otbody.insertRow(0);
//闭包函数,以防止无法在循环中定义值i
function tt(p,now) {
this.click=function(){
document.getElementById(div2).value+=now[p];
}
}
//判断开关情况决定显示字符
if((shift==true&&caps==true)||(shift==false&&caps==false)){
nowchar=valuechar1;
}else{
nowchar=valuechar2;
}
if(shift==false){
nownum=valuenum1;
}else{
nownum=valuenum2;
}
for(i=0;i<14;i++){
otbody.rows[0].insertCell(i);
otbody.rows[0].cells[i].innerText=nowchar[i];
var col=new tt(i,nowchar);
otbody.rows[0].cells[i].attachEvent("onclick",col.click);
}
//加入第二行
otbody.insertRow(1);
for(i=0;i<12;i++){
otbody.rows[1].insertCell(i);
otbody.rows[1].cells[i].innerText=nowchar[i+14];
var col=new tt(i+14,nowchar);
otbody.rows[1].cells[i].attachEvent("onclick",col.click);
}
//caps
otbody.rows[1].insertCell(12);
otbody.rows[1].cells[12].colSpan=2;
if(caps==true) {otbody.rows[1].cells[12].style.backgroundColor=downcolor;}
else {otbody.rows[1].cells[12].style.backgroundColor=upcolor;}
otbody.rows[1].cells[12].appendChild(document.createTextNode("caps"));
otbody.rows[1].cells[12].attachEvent("onclick",chcaps);
//加入第三行
otbody.insertRow(2);
for(i=0;i<10;i++){
otbody.rows[2].insertCell(i);
otbody.rows[2].cells[i].innerText=nownum[i];
var col=new tt(i,nownum);
otbody.rows[2].cells[i].attachEvent("onclick",col.click);
}
//shift
otbody.rows[2].insertCell(10);
otbody.rows[2].cells[10].colSpan=4;
if(shift==true) {otbody.rows[2].cells[10].style.backgroundColor=downcolor;}
else {otbody.rows[2].cells[10].style.backgroundColor=upcolor;}
otbody.rows[2].cells[10].attachEvent("onclick",chshift);
otbody.rows[2].cells[10].innerText="shift";
document.getElementById(div1).appendChild(otable);
//caps按钮执行函数
function chcaps(){
caps=!caps;
document.getElementById(div1).removeChild(otable);
createKeyBoard(div1,div2);
}
//shift按钮执行函数
function chshift(){
shift=!shift;
document.getElementById(div1).removeChild(otable);
createKeyBoard(div1,div2);
}
}
效果如下: