man*_*an1 113 javascript jquery
我无法找到答案的简单问题:如何使用JavaScript(或jQuery)取消选择可在网页上选择的任何文本?EG用户点击并拖动以突出显示一些文本 - 我想要一个deselectAll()函数来清除此选择.我该怎么写呢?
谢谢您的帮助.
Ger*_*der 193
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
Run Code Online (Sandbox Code Playgroud)
Tim*_*own 46
最好直接测试您想要的功能:
var sel = window.getSelection ? window.getSelection() : document.selection;
if (sel) {
if (sel.removeAllRanges) {
sel.removeAllRanges();
} else if (sel.empty) {
sel.empty();
}
}
Run Code Online (Sandbox Code Playgroud)
Cha*_*kal 13
我做了一些自己的研究.这是我写的和现在使用的功能:
(function deselect(){
var selection = ('getSelection' in window)
? window.getSelection()
: ('selection' in document)
? document.selection
: null;
if ('removeAllRanges' in selection) selection.removeAllRanges();
else if ('empty' in selection) selection.empty();
})();
Run Code Online (Sandbox Code Playgroud)
基本上,getSelection().removeAllRanges()目前所有现代浏览器(包括IE9 +)都支持.这显然是向前发展的正确方法.
兼容性问题占:
getSelection().empty()document.selection.empty()将这个选择功能包装起来以供重复使用可能是一个好主意.
function ScSelection(){
var sel=this;
var selection = sel.selection =
'getSelection' in window
? window.getSelection()
: 'selection' in document
? document.selection
: null;
sel.deselect = function(){
if ('removeAllRanges' in selection) selection.removeAllRanges();
else if ('empty' in selection) selection.empty();
return sel; // chainable :)
};
sel.getParentElement = function(){
if ('anchorNode' in selection) return selection.anchorNode.parentElement;
else return selection.createRange().parentElement();
};
}
// use it
var sel = new ScSelection;
var $parentSection = $(sel.getParentElement()).closest('section');
sel.deselect();
Run Code Online (Sandbox Code Playgroud)
我已将其设为社区维基,以便您可以为此添加功能,或在标准发展时更新内容.
2021 答案
removeAllRanges()大多数浏览器都支持,除了 macOS 或 iOS 上的 Safari。
empty()是所有浏览器(包括非常旧的浏览器,IE 除外)的别名removeAllRanges()并受其支持。这个别名是在规范中定义的,所以应该是安全的。
结论
只需使用getSelection().empty(). 不需要其他答案中的辅助函数、嵌套的三元 if、构造函数和诸如此类的 Ninja banzai。也许十年前需要,但现在不需要了。
如果你真的需要 IE 支持,你可以测试document.selection:
(window.getSelection ? window.getSelection() : document.selection).empty()
Run Code Online (Sandbox Code Playgroud)
(未在 IE 上测试)