简体   繁体   English

使用JavaScript在TextArea中检测自动缩进

[英]Detection for auto indentation in TextArea with JavaScript

I have a textarea where users can input text. 我有一个文本区域,用户可以在其中输入文本。

If the current line starts with 3 spaces and the user hits enter, it will automatically insert 3 spaces and set the cursor right after the spaces. 如果当前行以3个空格开头,并且用户按下Enter键,它将自动插入3个空格并将光标设置在空格之后。 (there may be text before or after) (可能在文本之前或之后)

How can I detect such pattern with JavaScript? 如何使用JavaScript检测这种模式?

Caret position in textarea, in characters from the start explains how to figure out where the caret is when the user hits enter so that you can check whether there are three spaces and a line break to the left. 文字区域中的插入符号位置(从一开始就以字符表示)说明了如何确定用户按下Enter键时插入符号的位置,以便您可以检查左侧是否有三个空格和一个换行符。

Enter key in textarea explains how to detect the Enter key in a textarea and take an action. textarea中的Enter键说明了如何检测textarea中Enter键并采取措施。

Once you have a listener hooked up and know the caret location is caret , you can do something like 接听了一个侦听器并知道插入符号的位置是caret ,您可以执行以下操作

if (/(?:^|[\r\n])   (?:[^\r\n ][^\r\n]*)?$/
    .test(myTextArea.value.substring(0, caret)) {
  ...
}

to take an action when there are exactly three spaces at the start of the current line. 在当前行的开头恰好有三个空格时采取措施。

To insert the 3 extra-spaces, you could do something like 要插入3个多余的空格,您可以执行以下操作

myTextArea.value = myTextArea.value.substring(0, caret)
    + "\n    " + myTextArea.value.substring(caret);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM