为了账号安全,请及时绑定邮箱和手机立即绑定

使用JavaScript清除文本选择

使用JavaScript清除文本选择

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

3 回答

?
翻阅古今

TA贡献1780条经验 获得超5个赞

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

}


查看完整回答
反对 回复 2019-12-18
?
心有法竹

TA贡献1866条经验 获得超5个赞

我自己做了一些研究。这是我最近编写并使用的函数:


(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 it

var sel = new ScSelection;

var $parentSection = $(sel.getParentElement()).closest('section');

sel.deselect();

我将其作为社区Wiki,以便您可以向其添加功能或随着标准的发展而更新。


查看完整回答
反对 回复 2019-12-18
  • 3 回答
  • 0 关注
  • 809 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信