Can a selection object be created without any user interaction?

后端 未结 1 639
面向向阳花
面向向阳花 2021-01-03 02:13

Can a Selection object be created without any user interaction? window.getSelection() does return a Selection object, but you can\'t modify() it u

相关标签:
1条回答
  • 2021-01-03 02:28

    If I understand what you're asking, then yes, you can programmatically set the selection using its addRange() method. For example, to select the whole of the document's <body> element when the page loads, you could do:

    function selectBody() {
        var range = document.createRange();
        range.selectNode(document.body);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
    
    window.onload = selectBody;
    

    This doesn't work on IE < 9, which has a whole different approach to ranges and selections.

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