【问题标题】:How to delete the selected words in the text?如何删除文本中选中的单词?
【发布时间】:2020-11-03 17:42:42
【问题描述】:

此代码选择单词并从中创建一个数组。但是我需要在被选中并添加到数组后删除单词。我想我需要使用 document.getSelection() 或 document.selection,但我不知道如何通过它们删除选定的单词。如果有人给我提示,我会很高兴。

<script>
let container;
var arr = [];
function get_selection() {
  
    var txt = '';
       if (document.getSelection) {
          txt = document.getSelection().toString();
                
                
            } 

            else if (document.selection) {
                txt = document.selection.createRange().text;
            }
             arr.push(txt);
            }
            }
           document.getElementById("txt").onclick = get_selection;

</script>

【问题讨论】:

  • 这个词/文本是否在 textarea 中?
  • 可以是textarea,但我用的是div contenteditable。

标签: javascript html jquery arrays if-statement


【解决方案1】:

您可以使用onselect 事件。在元素上或只是全局上,但你必须弄清楚你的目标不是例如。菜单元素:P。然后你可以使用textContent 如果你使用 contenteditable 并且只是在选择之前和之后的子字符串值并将内容值设置为它的总和。我使用 textarea,在大多数情况下使用 contenteditable 并不是最佳做法。

const selections = []

const handleOnSelect = (e) =>{
  const target = e.target;
  const start = target.selectionStart;
  const end = target.selectionEnd;
  const selection = target.value.substring(start, end);
  selections.push(selection);
  const pre = target.value.substring(0 , start);
  const post = target.value.substring(end);
  target.value = pre + post;
  
  console.log(selections)
}


window.addEventListener("load", ()=>{
   const target = document.getElementById("txt")
   target.addEventListener("select", handleOnSelect);
})
&lt;textarea id="txt"&gt; &lt;/textarea&gt;

【讨论】:

  • @NikN 如果您将我的答案标记为最佳答案会很好:)
猜你喜欢
  • 1970-01-01
  • 2019-10-27
  • 1970-01-01
  • 1970-01-01
  • 2013-02-15
  • 1970-01-01
  • 2016-01-19
  • 2017-07-18
  • 1970-01-01
相关资源
最近更新 更多