这些答案还不错,但是它们的局限性在于它们实际上不允许您输入数据。 在使用条形码读取器将数据输入到字段中时,我们遇到了类似的问题,但是我们想压低键盘。
这是我整理的,效果很好:
[HTTPS://code喷.IO/拨不进阿瑟/喷/QR QQ VD/]
input:
#hiddenField {
height:17px;
width:1px;
position:absolute;
margin-left:3px;
margin-top:2px;
border:none;
border-width:0px 0px 0px 1px;
}
#cursorMeasuringDiv {
position:absolute;
visibility:hidden;
margin:0px;
padding:0px;
}
#hiddenField:focus {
border:1px solid gray;
border-width:0px 0px 0px 1px;
outline:none;
animation-name: cursor;
animation-duration: 1s;
animation-iteration-count: infinite;
}
@keyframes cursor {
from {opacity:0;}
to {opacity:1;}
}
// whenever the visible field gets focused
$("#visibleField").bind("focus", function(e) {
// silently shift the focus to the hidden select box
$("#hiddenField").focus();
$("#cursorMeasuringDiv").css("font", $("#visibleField").css("font"));
});
// whenever the user types on his keyboard in the select box
// which is natively supported for jumping to an
$("#hiddenField").bind("keypress",function(e) {
// get the current value of the readonly field
var currentValue = $("#visibleField").val();
// and append the key the user pressed into that field
$("#visibleField").val(currentValue + e.key);
$("#cursorMeasuringDiv").text(currentValue + e.key);
// measure the width of the cursor offset
var offset = 3;
var textWidth = $("#cursorMeasuringDiv").width();
$("#hiddenField").css("marginLeft",Math.min(offset+textWidth,$("#visibleField").width()));
});
当您单击框时,它会模拟该框中的光标,但实际上会将焦点放在一个空的框上。 选择框自然允许按键支持跳转到列表中的某个元素,因此只需将按键重新路由到原始输入并偏移模拟光标即可。
这不适用于退格键,删除操作等,但是我们不需要这些。 您可能可以使用jQuery的触发器将键盘事件直接发送到某个地方的另一个输入框,但是我们不必为此烦恼,因此我没有这样做。