Can you set and/or change the user’s text selection in JavaScript?

后端 未结 1 1815
鱼传尺愫
鱼传尺愫 2020-11-27 06:50

In JavaScript, there are various methods for accessing the user’s text selection, and creating text selections (or ranges) — see http://www.quirksmode.org/dom/range_intro.ht

相关标签:
1条回答
  • 2020-11-27 07:25

    Yes. In all browsers you can get one or more Ranges or a TextRange from the user's selection, and both Range and TextRange have methods for changing the contents of the range.

    UPDATE

    You can set the user's selection by creating a Range and adding it to the Selection object in most browsers and by creating a TextRange and calling its select() method in IE <= 8.

    For example, to set the selection to encompass the contents of an element:

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

    There are also several methods of the Selection object that can be used to change the user's selection in non-IE browsers. If you can be more specific about how you want to change the selection then it will be easier to help.

    0 讨论(0)
提交回复
热议问题