0

我为我的应用程序创建了一个自定义@提及系统,我唯一的问题是开始输入@...,然后选择我要提及的用户,发生的情况是所选用户的名称刚刚添加到末尾textarea所以这个工作如果我只输入@但如果我输入@ja然后选择jason smith它现在会说@jaJason Smith我如何删除在@之后输入的任何文本然后添加我的字符​​串。仅供参考,这是在textarea

所以我当前的功能看起来像这样..

addMention(user: any): void {
  const textarea = document.querySelector('textarea');
  const mentionSelect = <HTMLElement>document.querySelector('.mention-container');
  const value = textarea.value; // Store the value
  textarea.value = `${textarea.value}${user.value}`; // Current Value
  mentionSelect.style.display = 'none'; // Hide the mention list
  this.message = textarea.value; // Make sure the new textarea value is stored in message
  textarea.focus(); // refocus
  textarea.value = ''; // clear
  textarea.value = value; // add the value back in
}

所以发生的事情是我只是通过添加用户名来更新 textarea 的值

编辑

我注意到这不是最好的方法,因为如果用户将光标移动到中间并键入@,名称将被添加到字符串的末尾而不是@所以我的问题是如何我替换了 @ 之后的字符串,但可以在 textarea 的任何地方进行操作??

任何帮助,将不胜感激!

4

2 回答 2

1

我跳过了getting dom部分,str指的是 的值textareaplaceholder指的是当前的智能感知,username指的是真实的用户名,position是可以通过以下方式确定的光标位置document.getElementById('textarea').selectionStart

const str = 'adfsaf @ adsfsad @ja!2123afd @eeeav @asedf';
const position = 20; // just after @ja, str[20] gives the space ' ' after @ja
const placeholder = '@ja'; // you should be able to get that dynamically.
const username = 'Jason Smith';  // you should be able to get that dynamically.

const idx = str.substring(0,position).indexOf(placeholder);
const output = `${str.substring(0,position - placeholder.length)}@${username} ${str.substring(position)}`;
console.log(output);

于 2018-07-18T01:41:37.303 回答
1

这是解决方案的简化版本。我没有你的设置来测试这个,当然有一种更清洁的方法来做这件事,但这应该让你知道去哪里。

addMention(user: { value: string }): void {
  const textArea = document.querySelector('textarea');
  const selection = textArea.selectionStart;
  let value = textarea.value;
  const str = value.substring(0, textArea.selectionStart);
  const index = str.lastIndexOf('@');
  const mention = str.substring(index);
  value = `${value.substring(0, index)}${user.value}${value.substring(index + mention.length)}`;
  textarea.value = value;
}
于 2018-07-18T01:24:54.620 回答