답변:
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 (에지)와 사파리에서 잘 작동합니다.
나는 내 스스로 조사를했다. 내가 작성하고 요즘 사용하고있는 함수는 다음과 같습니다.
(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();
사람들이 여기에 기능을 추가하거나 표준이 발전함에 따라 업데이트 할 수 있도록 이것을 커뮤니티 위키로 만들었습니다.
다음은 허용되는 답변이지만 두 줄의 코드입니다.
var selection = window.getSelection ? window.getSelection() : document.selection ? document.selection : null;
if(!!selection) selection.empty ? selection.empty() : selection.removeAllRanges();
유일한 removeAllRanges의 존재입니다 내가하지 않습니다 확인 -하지만 AFAIK 중 하나가 어떤 브라우저가 없다 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최종 사례 에서도 테스트 할 수 있습니다.