要素に focus() を使用すると、奇妙な問題が発生します。クリックした位置にカーソルを設定する必要があります。クリックされた位置を取得できますが、focus() イベントでこの位置に設定できないため、少し混乱しています。ここに私のコード:
function modify(value, item_ID, attr_NAME, obj_name) {
var item_id = item_ID;
var attr_name = attr_NAME;
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
$(value).addClass('ajax');
$(value).html(
'<input id="editbox"' + ' type="text" value="' + $(value).text()
+ '"/>');
$('#editbox').focus(function(e) {
var pos = GetCaretPosition(this);
alert(pos);
});
$('#editbox').keydown(function(event) {
if (event.which == 13) {
$(document).attr('helpAttr', false);
confirmAction(this.value, item_id, attr_name, obj_name);
}
});
$('#editbox').blur(
function() {
if ($(document).attr('helpAttr')
|| ($(document).attr('helpAttr') == undefined)) {
confirmAction(this.value, item_id, attr_name, obj_name);
} else {
$(document).attr('helpAttr', true);
}
});
}
//Got this from the Internet
function GetCaretPosition(ctrl) {
var CaretPos = 0;
// IE Support
if (document.selection) {
ctrl.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
私にとって奇妙なことは、 alert(pos) を使用すると、カーソルがこの位置に配置されることです。テキストボックスをクリックするたびにメッセージボックスが表示されると混乱するため、アラートを削除する解決策はありますか? ありがとう