【问题标题】:Wrap tags [start] [end] around selected text in textarea with Javascript使用 Javascript 将标签 [start] [end] 包裹在 textarea 中的选定文本周围
【发布时间】:2021-11-23 18:59:54
【问题描述】:

我有一个文本区域,用户可以在其中输入文本。使用按钮,他们应该能够使用自定义标签 [start] [end] 在此 textarea 中包装选定的文本。

<button onclick="addTags();">Add Tags to selected Text</button>

<textarea id="user-input" name="user-input" rows="4" cols="50"></textarea>

示例:如果 textarea 中的文本例如为“1 2 3”并且用户标记为“2”并单击按钮,则 textarea 中的结果应为“1 [start]2[end] 3”。

我正在努力让一段 javascript 工作,它会为我做这件事。

我玩过“window.getSelection()”。所以问题是:我的功能的正确方法是什么?

function addTags() {
...
}

【问题讨论】:

  • 您可以在一个 div 中使用多个输入。

标签: javascript html


【解决方案1】:

剪切文本:选择前、选择后、选择后。然后用标签重新组装。

document.getElementById("add-tag").onclick = () => {
  let txt = document.getElementById("user-input");
  const before = txt.value.substring(0, txt.selectionStart);
  const sel = txt.value.substring(txt.selectionStart, txt.selectionEnd);
  const after = txt.value.substring(txt.selectionEnd);
  txt.value = `${before}[start]${sel}[end]${after}`;
}; 
<button id="add-tag">Add Tags to selected Text</button>

<textarea id="user-input" name="user-input" rows="4" cols="50"></textarea>

TODO:处理未选择任何内容的情况。-

【讨论】:

  • 处理案例,简单的解决方案:if (txt.selectionStart === txt.selectionEnd) { return false; }
猜你喜欢
  • 2020-06-28
  • 2011-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
  • 2013-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多