DocumentOrShadowRoot.getSelection() - Web APIs 编辑

Experimental

This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The getSelection() property of the DocumentOrShadowRoot interface returns a Selection object representing the range of text selected by the user, or the current position of the caret.

Syntax

var selection = documentOrShadowRootInstance.getSelection()

Parameters

None.

Returns

A Selection object.

Example

function foo() {
    var selObj = document.getSelection();
    alert(selObj);
    var selRange = selObj.getRangeAt(0);
    // do stuff with the range
}

Notes

String representation of the Selection object

In JavaScript, when an object is passed to a function expecting a string (like Window.alert()), the object's toString() method is called and the returned value is passed to the function. This can make the object appear to be a string when used with other functions when it is really an object with properties and methods.

In the above example, selObj.toString() is automatically called when it is passed to Window.alert(). However, attempting to use a JavaScript String property or method such as length or substr directly on a Selection object results in an error if it does not have that property or method and may return unexpected results if it does. To use a Selection object as a string, call its toString() method directly:

var selectedText = selObj.toString();
  • selObj is a Selection object.
  • selectedText is a string (Selected text).

You can call Window.getSelection(), which works identically to Document.getSelection().

It is worth noting that currently getSelection() doesn't work on the content of <input> elements in Firefox. HTMLInputElement.setSelectionRange()) could be used to work around this.

Notice also the difference between selection and focus. Document.activeElement returns the focused element.

Specifications

SpecificationStatusComment
Shadow DOM
The definition of 'DocumentOrShadowRoot' in that specification.
ObsoleteInitial definition.

Browser Compatibility

BCD tables only load in the browser

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:59 次

字数:5083

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文