我想要获取 <input>
中光标的位置。这是我正在使用的代码:
$("input").keyup(function() {
$("<p>")
.html("Cursor position at " + $("input").caretPosition())
.appendTo("#test");
});
而caretPosition
被定义为(只是对selectionStart
的包装):
$.fn.caretPosition = function() {
if (!this.length) return;
var input = this[0];
try {
return input.selectionStart;
} catch(e) {
// No need for old IE support
return 0;
}
}
HTML
<input type="number" />
<div id="test">
</div>
很不幸,这在Chrome中无法正常工作,但在Firefox中可以。在Chrome中,它始终打印
0
。这使我认为chrome不支持selectionStart
,但我已经读到它支持selectionStart
。这得到了证实,如果我将type =" number "
更改为type =" text "
,它就开始工作了。如何使其在type="number"
的情况下能够在各种浏览器中保持一致?(不是IE,不需要支持它)。我已经阅读了https://dev59.com/onE85IYBdhLWcg3wMQhm#2897510,但它对我没有用(在Chrome中)。
Jsfiddle:http://jsfiddle.net/prankol57/zbaaky5z/2/ 编辑:我已确认
input中的selectionStart
返回true。那么为什么会抛出错误?
try {} catch
语句,就会检查控制台错误消息。 - soktinpk