【问题标题】:autocomplete with inline suggestion in textarea在 textarea 中使用内联建议自动完成
【发布时间】:2022-01-22 20:02:40
【问题描述】:

对于我的项目,我有一个文本区域

<textarea class="FormControl Composer-flexible TextEditor-editor" placeholder="message..." style="height: 189px;"></textarea>

我来这里是想问是否有办法在 textarea 本身内使用建议自动完成。例如,如果我开始写“这里”,我想看到“建议来了”的建议,如果我按 TAB 键或其他键,我可以选择建议。

有没有办法用普通的 javascript 做到这一点?

【问题讨论】:

    标签: javascript autocomplete


    【解决方案1】:

    你可以试试这个。

    const suggestions = [
                          "Here comes the suggestions", 
                          "I like pizza", 
                          "I'm a good programmer"
                        ]
    
    var textarea = document.getElementById('textarea')
    
    textarea.addEventListener('keyup', (e) => {
      var result = suggestions.filter(el => el.startsWith(textarea.value))
      console.log(result)
    })
        &lt;textarea class="FormControl Composer-flexible TextEditor-editor" id="textarea" placeholder="message..." style="height: 189px;"&gt;&lt;/textarea&gt;

    把结果放在一个盒子里。

    【讨论】:

    • 是的,像这样,但是我怎样才能把 che 结果放到 textarea 里面的一个盒子里?
    • 您可以尝试将建议放在一个 div 中并使用 css 将其移动到 textarea 内,或者您可以使用 result.forEach(suggestions => {textarea.value + = 建议} 但我认为这不是一个好主意
    【解决方案2】:

    这样的?

    注意我的代码区分大小写

    const texts = ["Here comes the suggestion", "Another suggestion"]
    
    document.getElementById("editor").addEventListener("keydown", function(e) {
      console.log(e.key, e.target.value)
      if (e.key === "Tab") {
        const val = this.value;
        texts.forEach(text => {
          if (text.startsWith(val)) this.value = text;
        })
      }
    })
    &lt;textarea id="editor" class="FormControl Composer-flexible TextEditor-editor" placeholder="message..." style="height: 189px;"&gt;&lt;/textarea&gt;

    【讨论】:

      猜你喜欢
      • 2015-12-16
      • 2012-09-21
      • 2012-03-17
      • 2017-08-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2011-06-08
      相关资源
      最近更新 更多