3 回答

TA貢獻1780條經(jīng)驗 獲得超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();
}

TA貢獻1866條經(jīng)驗 獲得超5個贊
我自己做了一些研究。這是我最近編寫并使用的函數(shù):
(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()當(dāng)前所有現(xiàn)代瀏覽器(包括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();
我將其作為社區(qū)Wiki,以便您可以向其添加功能或隨著標(biāo)準(zhǔn)的發(fā)展而更新。
添加回答
舉報