可以在没有任何用户交互的情况下创建选择对象吗 [英] Can a selection object be created without any user interaction?
问题描述
可以在没有任何用户互动的情况下创建选择对象吗? window.getSelection()
确实返回 Selection
对象,但你不能 modify()除非用户进行了某种选择。
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.
是否可以创建一个从页面的第一个元素开始然后能够 modify()$ c的选择$ c>它,无需用户做任何事情?
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?
示例: http://jsfiddle.net/niklasvh/L5M3U/
它不会在页面加载时选择任何内容,但是如果你点击它确实做出选择的任何事情。
It doesn't select anything on page load, but if you click on anything it does make a selection.
推荐答案
如果我理解你在问什么,那么是的,你可以通过编程设置使用 addRange()
方法进行选择。例如,要在页面加载时选择整个文档的< body>
元素,您可以执行以下操作:
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;
这不适用于IE< 9,它有一个完全不同的范围和选择方法。
This doesn't work on IE < 9, which has a whole different approach to ranges and selections.
这篇关于可以在没有任何用户交互的情况下创建选择对象吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!