您可以在JavaScript中设置和/或更改用户的文本选择吗? [英] Can you set and/or change the user’s text selection in JavaScript?

查看:87
本文介绍了您可以在JavaScript中设置和/或更改用户的文本选择吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,有多种方法可以访问用户的文本选择,以及创建文本选择(或范围) - 请参阅 http://www.quirksmode.org/dom/range_intro.html

In JavaScript, there are various methods for accessing the user’s text selection, and creating text selections (or ranges) — see http://www.quirksmode.org/dom/range_intro.html.

根据该页面,您可以通过编程方式创建范围,并访问其中的文本。但这样做并不会改变用户的文本选择,或者如果用户没有选择文本,则会使用户有一些选定的文本。

As per that page, you can programmatically create a range, and access the text within that. But doing this doesn’t change the user’s text selection, or make the user have some selected text if they don’t already.

你可以设置和/或更改用户在JavaScript中的文本选择?

Can you set and/or change the user’s text selection in JavaScript?

推荐答案

是的。在所有浏览器中,您可以从用户的选择中获得一个或多个 Range s或 TextRange ,以及范围 TextRange 有更改范围内容的方法。

Yes. In all browsers you can get one or more Ranges or a TextRange from the user's selection, and both Range and TextRange have methods for changing the contents of the range.

更新

您可以通过创建范围并添加它来设置用户的选择到大多数浏览器中的选择对象,并创建 TextRange 并调用其 select() IE中的方法< = 8。

You can set the user's selection by creating a Range and adding it to the Selection object in most browsers and by creating a TextRange and calling its select() method in IE <= 8.

例如,要将选择设置为包含元素的内容:

For example, to set the selection to encompass the contents of an element:

function selectElementContents(el) {
    if (window.getSelection && document.createRange) {
        var sel = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(el);
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (document.selection && document.body.createTextRange) {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.select();
    }
}

选择 可用于更改用户的对象在非IE浏览器中选择。如果您可以更具体地了解如何更改选择,那么将更容易提供帮助。

There are also several methods of the Selection object that can be used to change the user's selection in non-IE browsers. If you can be more specific about how you want to change the selection then it will be easier to help.

这篇关于您可以在JavaScript中设置和/或更改用户的文本选择吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆