我找不到答案的简单问题:
我如何使用JavaScript(或jQuery的),以取消其可以是任何文字选择在网页上?
EG 用户单击并拖动以突出显示一些文本 - 我想要一个函数 deselectAll() 来清除此选择。我该怎么写呢?
谢谢您的帮助。
我找不到答案的简单问题:
我如何使用JavaScript(或jQuery的),以取消其可以是任何文字选择在网页上?
EG 用户单击并拖动以突出显示一些文本 - 我想要一个函数 deselectAll() 来清除此选择。我该怎么写呢?
谢谢您的帮助。
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();
}
最好直接测试你想要的功能:
var sel = window.getSelection ? window.getSelection() : document.selection;
if (sel) {
    if (sel.removeAllRanges) {
        sel.removeAllRanges();
    } else if (sel.empty) {
        sel.empty();
    }
}
我自己做了一些研究。这是我最近编写并使用的函数:
(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();
})();
基本上,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();
我已经把它变成了一个社区维基,这样你们就可以向它添加功能,或者随着标准的发展更新内容。
2021 答案
removeAllRanges()大多数浏览器都支持,除了 macOS 或 iOS 上的 Safari。
empty()是所有浏览器的别名removeAllRanges()并受其支持,包括非常旧的浏览器,IE 除外。这个别名是在规范中定义的,所以应该可以安全地依赖。
结论
只需使用getSelection().empty(). 不需要其他答案中的辅助函数、嵌套的三元 if、构造函数和诸如此类的 Ninja banzai。也许十年前需要,但现在不需要了。
如果你真的需要 IE 支持,你可以测试document.selection:
(window.getSelection ? window.getSelection() : document.selection).empty()
(未在 IE 上测试)
这是公认的答案,但在两行代码中:
var selection = window.getSelection ? window.getSelection() : document.selection ? document.selection : null;
if(!!selection) selection.empty ? selection.empty() : selection.removeAllRanges();
我不做的唯一检查是 removeAllRanges 的存在 - 但 AFAIK 没有浏览器具有window.getSelection或document.selection但不具有该属性的.empty或.removeAllRanges。