JavaScript Set Window selection

限于喜欢 提交于 2019-11-26 22:49:36

问题


In JavaScript, there is a method window.getSelection(), that lets me get the current selection that the user has made.

Is there a corresponding function, something like window.setSelection(), that will let me set, or clear, the current selection?


回答1:


Maybe this will do it:

window.selection.clear();

Crossbrowser version:

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



回答2:


Clearing the selection in all major browsers:

function clearSelection() {
    if (window.getSelection) {
        window.getSelection().removeAllRanges();
    } else if (document.selection) {
        document.selection.empty();
    }
}

Selecting content requires use of DOM Range and Selection objects in most browsers and TextRange objects in IE < 9. Here's a simple cross-browser example that selects the contents of a particular element:

function selectElement(element) {
    if (window.getSelection) {
        var sel = window.getSelection();
        sel.removeAllRanges();
        var range = document.createRange();
        range.selectNodeContents(element);
        sel.addRange(range);
    } else if (document.selection) {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(element);
        textRange.select();
    }
}



回答3:


In browsers that support the "selection" and "range" stuff, you'll want to create a range object and then set its start/end. The Mozilla documentation for the "range" object has a lot of information.

Chrome doesn't support this, at least not with that API, and I bet Safari doesn't either.

edit — thanks to @Tim Down for noting that WebKit (Chrome & Safari) do indeed support this, which means my jsfiddle had a typo or something!



来源:https://stackoverflow.com/questions/6190143/javascript-set-window-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!