js 取消选中的文字
封面图
•
2025-10-02
•
JavaScript
190
0
0
0
在 JavaScript 中,“取消选中的文字”通常指的是**取消用户当前选中的文本**。这在一些富文本编辑器、输入框或内容可编辑的区域中比较常见。 以下是几种常见的方法来实现“取消选中的文字”: --- ### ✅ 方法一:使用 `window.getSelection().removeAllRanges()`(适用于网页中的文本) ```javascript function deselectText() { if (window.getSelection) { window.getSelection().removeAllRanges(); } else if (document.selection && document.selection.clear) { document.selection.clear(); // 兼容旧版 IE } } ``` **说明**: - `window.getSelection()` 获取当前选区对象。 - `removeAllRanges()` 移除所有选区,相当于取消选中。 --- ### ✅ 方法二:在 `<input>` 或 `<textarea>` 中取消选中 如果你是在 `<input>` 或 `<textarea>` 中操作,可以使用以下方式: ```javascript document.querySelector('input').blur(); // 使输入框失去焦点,自动取消选中 ``` 或者: ```javascript document.querySelector('input').setSelectionRange(0, 0); // 设置光标位置,取消选中 ``` --- ### ✅ 方法三:在 contenteditable 区域中取消选中 如果你在 `contenteditable` 的 div 中操作: ```html <div id="editor" contenteditable="true">可编辑内容</div> ``` ```javascript function deselectContentEditable() { const range = document.createRange(); const sel = window.getSelection(); range.setStart(document.getElementById("editor"), 0); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } ``` --- ### ✅ 使用 jQuery(如果已引入) ```javascript function deselectText() { if (window.getSelection) { window.getSelection().removeAllRanges(); } else if (document.selection) { document.selection.empty(); } } ``` --- ### 📌 总结 | 场景 | 方法 | |------|------| | 普通网页文本 | `window.getSelection().removeAllRanges();` | | `<input>`/`<textarea>` | `.blur()` 或 `.setSelectionRange(0,0)` | | `contenteditable` 区域 | 创建一个空范围并移除所有选区 | --- 如果你有具体的场景(比如在某个编辑器中),可以告诉我,我可以提供更精确的方法!
上一篇:
js获取年月日
下一篇:
js 浏览器缓存机制
标题录入,一次不能超过6条
留言
评论