为什么这段代码不起作用?
http://sandbox.phpcode.eu/g/5db40.php
<form>
<textarea></textarea>
</form>
<script>
$(function(){
$("textarea").keydown(function(e){
if (e.keyCode == 9){
$("textarea").selectionStart.append(" ");
e.preventDefault();
}
});
});
</script>
您必须在文本区域上按 TAB
问题是它不执行/附加四个空格,并且执行默认浏览器操作(切换到 Chrome 中的地址选项卡)
想法?
最佳答案
相关于this问题,尝试:
$(function () {
$("textarea").keydown(function (e) {
if (e.keyCode == 9) {
e.preventDefault();
var $this = $(this);
var pos = $this[0].selectionStart;
$this.val($this.val().substring(0, pos) + " " + $this.val().substring(pos));
$this.setCursorPosition(pos + 4);
}
});
});
并添加来自 this 的 JQuery发布。
new function($) {
$.fn.setCursorPosition = function(pos) {
if ($(this).get(0).setSelectionRange) {
$(this).get(0).setSelectionRange(pos, pos);
} else if ($(this).get(0).createTextRange) {
var range = $(this).get(0).createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
}(jQuery);
关于javascript - 查找文本区域中光标的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6960445/