使用JavaScript清除文本选择

我找不到答案的简单问题:如何使用JavaScript(或jQuery)取消选择可能在网页上选择的任何文本?EG用户单击并拖动以突出显示一些文本-我想要一个函数deselectAll()来清除此选择。我应该怎么写呢?



人到中年有点甜
浏览 811回答 3
3回答

翻阅古今

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();}

心有法竹

我自己做了一些研究。这是我最近编写并使用的函数:(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 +)都支持。显然,这是前进的正确方法。兼容性问题占:使用旧版本的Chrome和Safari getSelection().empty()IE8及以下版本 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 itvar sel = new ScSelection;var $parentSection = $(sel.getParentElement()).closest('section');sel.deselect();我将其作为社区Wiki,以便您可以向其添加功能或随着标准的发展而更新。
打开App,查看更多内容
随时随地看视频慕课网APP