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

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,以便您可以向其添加功能或随着标准的发展而更新。
添加回答
举报