Answers:
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();
}
window.getSelection().removeAllRanges();
在IE(edge)和Safari中可以正常工作。
我自己做了一些研究。这是我最近编写并使用的函数:
(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 +)都支持。显然,这是前进的正确方法。
兼容性问题占:
getSelection().empty()
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,以便您可以向其添加功能或随着标准的发展而更新。
这是可接受的答案,但是使用两行代码:
var selection = window.getSelection ? window.getSelection() : document.selection ? document.selection : null;
if(!!selection) selection.empty ? selection.empty() : selection.removeAllRanges();
该只检查我不这样做是removeAllRanges的存在-但据我所知,没有浏览器,无论是有window.getSelection
或document.selection
,但不具有任何一个.empty
或.removeAllRanges
该属性。
window.getSelection()使您可以访问选定的文本,从那里可以进行一些操作。
阅读更多:开发人员Mozilla DOM选择
将此添加到脚本中可防止右键单击和选择文本。
可以将异常添加到var'om'中。
var d=document,om=['input','textarea','select'];;
function ie(){if(d.all){(mg);return false;}}function mz(e){if(d.layers||(d.getElementById&&!d.all)){if(e.which==2||e.which==3){(mg);return false;}}}if(d.layers){d.captureEvents(Event.mousedown);d.onmousedown=mz;}else{d.onmouseup=mz;d.oncontextmenu=ie;}d.oncontextmenu=new Function('return false');om=om.join('|');function ds(e){if(om.indexOf(e.target.tagName.toLowerCase())==-1);return false;}function rn(){return true;}if(typeof d.onselectstart!='undefined')d.onselectstart=new Function('return false');else{d.onmousedown=ds;d.onmouseup=rn;}
document.selection
意味着存在其empty()
方法。您已经在所有其他情况下测试了该方法,因此您也可能会empty
在最后一种情况下进行测试。