これらの回答は悪くはありませんが、実際にはデータを入力できないという制限があります。バーコード リーダーを使用してフィールドにデータを入力するという同様の問題がありましたが、キーボードを非表示にしたかったのです。
これは私がまとめたものです、それはかなりうまくいきます:
https://codepen.io/bobjase/pen/QrQQvd/
<!-- must be a select box with no children to suppress the keyboard -->
input: <select id="hiddenField" />
<span id="fakecursor" />
<input type="text" readonly="readonly" id="visibleField" />
<div id="cursorMeasuringDiv" />
#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 <option>
$("#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()));
});
ボックス内をクリックすると、その<input>
ボックス内のカーソルがシミュレートされますが、実際には空の<select>
ボックスにフォーカスが置かれます。選択ボックスは、当然のことながら、キー押下でリスト内の要素へのジャンプをサポートできるようにするため、キー押下を元の入力に再ルーティングし、シミュレートされたカーソルをオフセットするだけで済みました。
これは、バックスペース、削除などには機能しません...しかし、それらは必要ありませんでした。jQuery のトリガーを使用して、キーボード イベントをどこか別の入力ボックスに直接送信することもできますが、それを気にする必要はなかったので、私はそれを行いませんでした。