首页 > 解决方案 > 我们可以使用 getSelection 和 document.selection 来发现一个单词来删除它吗?

问题描述

我们可以使用 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>

标签: javascripthtmljqueryif-statementgetselection

解决方案


试试这个代码

let container;
var arr = [];
function get_selection(e) {

   var txt = '';
   if (document.getSelection) {
      txt = document.getSelection().toString();
   }else if (document.selection) {
         txt = document.selection.createRange().text;
   }
   e.target.innerText = e.target.textContent.replace(e.target.textContent.substring(e.target.textContent.indexOf(txt), txt.length),"")
    
}

document.getElementById("txt").onclick = get_selection;

该程序不会放入数组而是删除选择,您可以将选择推送到数组中并在需要时将其删除。

这是一个演示


推荐阅读