亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用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 關注
  • 912 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號