以编程方式选择可疑的HTML元素中的文本? [英] Programmatically select text in a contenteditable HTML element?

查看:155
本文介绍了以编程方式选择可疑的HTML元素中的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,可以以编程方式在输入 textarea 元素中选择文本。您可以使用 ipt.focus()聚焦输入,然后使用 ipt.select() 。您甚至可以使用 ipt.setSelectionRange(from,to)选择特定范围)

In JavaScript, it's possible to programmatically select text in an input or textarea element. You can focus an input with ipt.focus(), and then select its contents with ipt.select(). You can even select a specific range with ipt.setSelectionRange(from,to).

我的问题是:有没有办法在 contenteditable中执行此操作元素呢?

My question is: is there any way to do this in a contenteditable element too?

我发现我可以 elem.focus(),将插入符号放在<$ c $中c> contenteditable 元素,但随后运行 elem.select()不起作用(也不是 setSelectionRange )。我在网上找不到任何关于它的内容,但也许我正在寻找错误的东西...

I found that I can do elem.focus(), to put the caret in a contenteditable element, but subsequently running elem.select() doesn't work (and nor does setSelectionRange). I can't find anything on the web about it, but maybe I'm searching for the wrong thing...

顺便说一句,如果它有任何区别,我只需要它在谷歌浏览器中工作,因为这是Chrome扩展程序。

By the way, if it makes any difference, I only need it to work in Google Chrome, as this is for a Chrome extension.

推荐答案

如果你想选择全部Chrome中的元素内容(是否可信),具体如何。这也适用于Firefox,Safari 3 +,Opera 9+(也可能是早期版本)和IE 9.您还可以创建字符级别的选择。您需要的API是DOM范围(当前规范是 DOM Level 2 ,另请参阅 MDN )和选择,指定为部分一个新的范围规范 MDN文档)。

If you want to select all the content of an element (contenteditable or not) in Chrome, here's how. This will also work in Firefox, Safari 3+, Opera 9+ (possibly earlier versions too) and IE 9. You can also create selections down to the character level. The APIs you need are DOM Range (current spec is DOM Level 2, see also MDN) and Selection, which is being specified as part of a new Range spec (MDN docs).

function selectElementContents(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
}

var el = document.getElementById("foo");
selectElementContents(el);

这篇关于以编程方式选择可疑的HTML元素中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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