您好我已经编写了这个JS脚本来捕获TAB按键捕获。 它捕获并在" pre"中的当前指针位置插入\ t。标签
$m = jQuery.noConflict();
$m(document).keydown(function(event) {
var keyCode = event.which;
if(keyCode == 9) {
// alert(); if this is there the code works, but if i remove this the code doesn't work, i dont want to alert user every time he hits TAB
// get caret position/selection
var start = this.selectionStart;
var end = this.selectionEnd;
var $this = $m(this);
var value = $this.val();
// set textarea value to: text before caret + tab + text after caret
$this.val(value.substring(0, start)
+ "\t"
+ value.substring(end));
// put caret at right position again (add one for the tab)
this.selectionStart = this.selectionEnd = start + 1;
// prevent the focus lose
event.preventDefault();
}
});
<div class="masterContainer" onclick="setFocusDiv();">
<div class="lined"></div>
<pre id="inputId" class="nonlined" contenteditable="true" onkeyup="setLineNu();" onfocus="setLineNu();"></pre>
</div>
但我的问题是,当我在脚本中插入一个警报时,它完全正常工作并插入\ t但是当我删除警报时它不起作用。此外还有焦点事件,但在TAB媒体报道后焦点丢失。
答案 0 :(得分:0)
您需要在preventDefault()
而不是event
this