JavaScript Set Window选择
在JavaScript中,有一个方法window.getSelection()
,它允许我获取用户所做的当前选择。
是否有相应的函数,比如window.setSelection()
,它可以让我设置或清除当前选择?
也许这样做会:
window.selection.clear();
Crossbrowser版本:
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(); }
清除所有主流浏览器中的选择:
function clearSelection() { if (window.getSelection) { window.getSelection().removeAllRanges(); } else if (document.selection) { document.selection.empty(); } }
选择内容需要在大多数浏览器中使用DOM Range
和Selection
对象,在IE <9中使用TextRange
对象。这是一个简单的跨浏览器示例,用于选择特定元素的内容:
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(); } }
在支持“选择”和“范围”内容的浏览器中,您需要创建一个范围对象,然后设置其开始/结束。 “范围”对象的Mozilla文档有很多信息。
Chrome不支持此function,至少不支持该API,我敢打赌Safari也不支持。
编辑 – 感谢@Tim Down注意到WebKit(Chrome和Safari)确实支持这一点,这意味着我的jsfiddle有一个错字或其他东西!