javascript - 我们可以使用 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>
解决方案
试试这个代码
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;
该程序不会放入数组而是删除选择,您可以将选择推送到数组中并在需要时将其删除。
这是一个演示
推荐阅读
- javascript - 如何从具有特定比例的数组中选择一个随机值?
- c++ - 给定一个迭代器,用正确的 size_type 声明一个索引
- javascript - 计算数组中 date() 条目之间的平均差异(以毫秒为单位)
- java - 如何在Java中获取字符串中的特定单词
- c# - HttpClient / HttpRequestMessage 向标头添加空格
- java - Java 正则表达式匹配一个反斜杠
- asp.net-core - 将实体框架项目升级到最新的 netcore SDK
- javascript - 不能一键下载2个文件(不同的url)
- ruby-on-rails - MySQL 的 CircleCI 配置问题
- swift - Swift中负数的算术运算符