[英]How do you keep the tab level in a textarea when pressing enter?
當用戶按下回車鍵時,我希望光標移到新行,但如果它們當前縮進了兩個制表符,則光標應保持縮進兩個制表符。
我已經實現了忽略選項卡事件來停止頁面內的焦點移動,所以我現在只是在尋找將選項卡級別保持在新行上的邏輯。
if(e.keyCode === 13){
//Logic here
}
$("textarea").keydown(function(e){
if(e.keyCode == 13){
// assuming 'this' is textarea
var cursorPos = this.selectionStart;
var curentLine = this.value.substr(0, this.selectionStart).split("\n").pop();
var indent = curentLine.match(/^\s*/)[0];
var value = this.value;
var textBefore = value.substring(0, cursorPos );
var textAfter = value.substring( cursorPos, value.length );
e.preventDefault(); // avoid creating a new line since we do it ourself
this.value = textBefore + "\n" + indent + textAfter;
setCaretPosition(this, cursorPos + indent.length + 1); // +1 is for the \n
}
});
function setCaretPosition(ctrl, pos)
{
if(ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
必須說基於一鍵按下的解決方案是晦澀難懂的,因為人們也喜歡粘貼文本。 改用input
事件。 你可以像這樣在jQuery中制作它:
$('textarea').on('input', function(e) { var el = $(this); var cur = $(this).prop('selectionStart'); // retrieve current caret position before setting value var text = $(this).val(); var newText = text.replace(/^(.+)\\t+/mg, '$1'); // remove intermediate tabs newText = newText.replace(/^([^\\t]*)$/mg, '\\t\\t$1'); // add two tabs in the beginning of each line if (newText != text) { // If text changed... $(this).val(newText); // finally set value // and reset caret position shifted right by one symbol $(this).prop('selectionStart', cur + 1); $(this).prop('selectionEnd', cur + 1); } });
<textarea></textarea> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
順便說一句,我懶得解釋如何查看用戶所需的標簽計數,這個只是在每一行插入兩個標簽。
我通過使用execCommand 'insertText'
而不是修改textarea.value
改進了Endless的答案。
好處:
缺點:
$('textarea').on('keydown', function(e) { if (e.which == 13) { // [ENTER] key event.preventDefault() // We will add newline ourselves. var start = this.selectionStart; var currentLine = this.value.slice(0, start).split('\\n').pop(); var newlineIndent = '\\n' + currentLine.match(/^\\s*/)[0]; if (!document.execCommand('insertText', false, newlineIndent)) { // Add fallback for Firefox browser: // Modify this.value and update cursor position as per solution by Endless. } } });
<textarea style="width:99%;height:99px;"> I am indented by 8 spaces. I am indented by a tab.</textarea> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.