我正在尝试模拟textarea中的tabbing,到目前为止tab选项工作但我不太确定如何使backtab工作。有关如何执行此操作的任何建议或更好的方法都会有所帮助。
$('textarea').on('keydown mousedown', function(e){
var val = this.value,
start = this.selectionStart,
end = this.selectionEnd;
if (e.shiftKey) {
console.log('shift')
if (e.which == 9 || e.keyCode == 9) {
console.log('shift + tab')
e.preventDefault();
this.value = val.substring(0, start) + '\t' + val.substring(end);
}
} else if (e.which == 9 || e.keyCode == 9) {
console.log('tab')
e.preventDefault();
this.value = val.substring(0, start) + '\t' + val.substring(end);
}
})
答案 0 :(得分:2)
这可能会让你开始。
$('textarea').on('keydown mousedown', function(e) {
var val = this.value,
start = this.selectionStart,
end = this.selectionEnd;
if (e.which == 9 || e.keyCode == 9) {
e.preventDefault();
if (e.shiftKey) {
var firstTabPoint = val.lastIndexOf('\n', start) + 1;
if (val.substring(firstTabPoint, firstTabPoint + 1) == '\t') {
var startString = val.substr(0, firstTabPoint);
var endString = val.substr(firstTabPoint + 1);
this.value = startString + endString;
this.setSelectionRange(start - 1, end - 1);
}
} else {
this.value = val.substring(0, start) + '\t' + val.substring(end);
this.setSelectionRange(start + 1, end + 1);
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="20" cols="100">
Add some lines in here, tab them, and then try untabbing.
</textarea>
作为旁注,如果您正在制作文本编辑器应用程序,则可以查看属性contenteditable="true"
。