简体   繁体   中英

Can a selection object be created without any user interaction?

Can a Selection object be created without any user interaction? window.getSelection() does return a Selection object, but you can't modify() it unless the user has some sort of selection made.

Is it possible to create a selection which starts at the very first element on the page and then be able to modify() it, without the need for the user to do anything?

Example: http://jsfiddle.net/niklasvh/L5M3U/

It doesn't select anything on page load, but if you click on anything it does make a selection.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM