現在、テキストを安全に選択できる要素は次のとおりです。
<input type="text|search|password|tel|url">
説明されているように:
whatwg:selectionStart属性。
HTMLInputElementインターフェースのドキュメントを読んで、入力要素を詳しく調べることもできます。
この「問題」を安全に克服するために、今のところ最善の方法は、<input type="text">
数字のみを受け入れるマスク/制約を処理して適用することです。要件を満たすプラグインがいくつかあります。
以前のプラグインの1つのライブデモをここで見ることができます:
安全に使用したい場合はselectionStart
、それをサポートする要素を確認できます(入力タイプの属性を参照)。
実装
var _fixSelection = (function() {
var _SELECTABLE_TYPES = /text|password|search|tel|url/;
return function fixSelection (dom, fn) {
var validType = _SELECTABLE_TYPES.test(dom.type),
selection = {
start: validType ? dom.selectionStart : 0,
end: validType ? dom.selectionEnd : 0
};
if (validType && fn instanceof Function) fn(dom);
return selection;
};
}());
function getCaretPosition (dom) {
var selection, sel;
if ('selectionStart' in dom) {
return _fixSelection(dom).start;
} else {
selection = document.selection;
if (selection) {
sel = selection.createRange();
sel.moveStart('character', -dom.value.length);
return sel.text.length;
}
}
return -1;
}
使用法
var box = document.getElementById("price"),
pos = getCaretPosition(box);
console.log("position: ", pos);
上記の例はここにあります:jsu.fnGetCaretPosition()