在文本输入字段中获取光标位置(以字符为单位)如何从输入字段中获得插入符号位置?我在谷歌上发现了一些零碎的东西,但没有防弹作用。基本上,像jQuery插件这样的东西是理想的,所以我可以简单地做。$("#myinput").caretPosition()
4 回答
汪汪一只猫
TA贡献1898条经验 获得超8个赞
更容易更新:
field.selectionStart
旧答案:
/* ** Returns the caret (cursor) position of the specified text field (oField). ** Return value range is 0-oField.value.length. */function doGetCaretPosition (oField) { // Initialize var iCaretPos = 0; // IE Support if (document.selection) { // Set focus on the element oField.focus(); // To get cursor position, get empty selection range var oSel = document.selection.createRange(); // Move selection start to 0 position oSel.moveStart('character', -oField.value.length); // The caret position is selection length iCaretPos = oSel.text.length; } // Firefox support else if (oField.selectionStart || oField.selectionStart == '0') iCaretPos = oField.selectionDirection=='backward' ? oField.selectionStart : oField.selectionEnd; // Return results return iCaretPos;}
跃然一笑
TA贡献1826条经验 获得超6个赞
(function($) { $.fn.getCursorPosition = function() { var input = this.get(0); if (!input) return; // No (input) element found if ('selectionStart' in input) { // Standard-compliant browsers return input.selectionStart; } else if (document.selection) { // IE input.focus(); var sel = document.selection.createRange(); var selLen = document.selection.createRange().text.length; sel.moveStart('character', -input.value.length); return sel.text.length - selLen; } }})(jQuery);
回首忆惘然
TA贡献1847条经验 获得超11个赞
很容易
更新答复
selectionStart
document.getElementById('foobar').addEventListener('keyup', e => {
console.log('Caret at: ', e.target.selectionStart)
})
<input id="foobar" />
猛跑小猪
TA贡献1858条经验 获得超8个赞
有一个非常简单的解决方案
<html><head><script> function f1(el) { var val = el.value; alert(val.slice(0, el.selectionStart).length);}</script></head><body><input type=text id=t1 value=abcd> <button onclick="f1(document.getElementById('t1'))">check position</button></body></html>
添加回答
举报
0/150
提交
取消