我正在尝试创建一个html / javascript键盘来填充输入
问题在于,当用户在输入中间进行选择并单击任何键盘按钮时,字符将被添加到输入的末尾。
<input type="text" id="input"/>
<button onclick="document.getElementById('input').value+=this.innerHTML;document.getElementById('input').focus()">A</button>
<button onclick="document.getElementById('input').value+=this.innerHTML;document.getElementById('input').focus()">B</button>
<button onclick="document.getElementById('input').value+=this.innerHTML;document.getElementById('input').focus()">C</button>
任何解决方案
Jsfiddle here
最佳答案
完整示例(缺少一些数字等。)
可以指向您想要的任何地方。
动态创建键盘,仅一个事件监听器
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>keyboard</title>
<style>
body>div{
clear:both;
overflow:auto;
border:2px solid grey;
}
body>div>div{
width:64px;line-height:64px;float:left;
border:1px solid grey;
text-align:center;
}
</style>
<script>
(function(W){
var D,K,I,pos=0;
function init(){
D=W.document;
I=document.createElement('input');
document.body.appendChild(I);
K=D.createElement('div');
K.id="k";
K.addEventListener('click',h,false);
var L='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'.split(','),
l=L.length;
for(var a=0;a<l;a++){
K.appendChild(document.createElement('div')).innerText=L[a];
}
document.body.appendChild(K);
}
function h(e){
if(e.target.parentNode.id=='k'){
pos=(I.selectionStart?I.selectionStart:pos?pos:0);
var end=I.selectionEnd?I.selectionEnd:pos;
I.value=I.value.substr(0,pos)+
e.target.innerText+
I.value.substr(end);
I.focus();
pos++
I.selectionStart=pos;
I.selectionEnd=pos;
}
}
W.addEventListener('load',init,false);
})(window)
</script>
</head>
<body>
</body>
</html>
ps:我在Chrome中测试过。
编辑
唯一不起作用的是,如果您选择一个文本并在删除之前写该文本,则该文本将从选择开始的地方开始,并且将其他选定的字母保留在原处。
编辑2您期望的所有内容