如何使用javascript在页面上选择任意文本?

如何使用javascript在页面上选择任意文本?,javascript,webkit,Javascript,Webkit,假设我有一个contentEditablediv,用户可以编辑和更改其中的文本和元素。如何使用javascript任意更改此div中的选择?我所说的“更改”并不是指“更改用户所选内容”,而是指实际更改所选内容。然后,用户应该能够在所选内容上键入内容,并将其替换为其他内容 这应该考虑到我可能希望跨元素选择文本。例如: <p>Some text <span>goes</span> here.</p> 这里有一些文字 例如,我可能想选择“Some t

假设我有一个contentEditable
div
,用户可以编辑和更改其中的文本和元素。如何使用javascript任意更改此
div
中的选择?我所说的“更改”并不是指“更改用户所选内容”,而是指实际更改所选内容。然后,用户应该能够在所选内容上键入内容,并将其替换为其他内容

这应该考虑到我可能希望跨元素选择文本。例如:

<p>Some text <span>goes</span> here.</p>
这里有一些文字

例如,我可能想选择“Some text go”,或者选择
中的所有内容

这只需要在Safari/Webkit中使用


提前谢谢。作为一名本地代码开发人员,我发现DOM和Javascript总体上相当令人沮丧。

您可以使用
document.getElementById('your_text_id')。setSelectionRange(start,end)
您可以使用
Math.random()
start
end
生成随机数,除非您需要自己编写,否则您可能需要查看tinyMCE,因为它是javascript中一个很好的所见即所得编辑器

为了做到这一点,您可能希望看到如下内容:

这些也可能有帮助:


你要做的事情会很复杂,因为你需要选择所选区域,删除所有标记,然后放入所选区域所需的标记。

只需详细回答我自己的问题,这样任何搜索类似内容的人都不必去其他地方寻找

我最终使用的代码是这样的:

var range = document.createRange();
range.setStart( <get the node the selection starts in>, <char offset in that node> );
range.setEnd( <get the node the selection ends in>, <char offset in that node> ); 

window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
var range=document.createRange();
range.setStart(,);
射程。设定值(,);
getSelection().removeAllRanges();
window.getSelection().addRange(范围);

非常感谢詹姆斯·布莱克为我指明了正确的方向。

虽然@Lucas的答案很好,但仍有许多不足之处可以让你成功地使用它。选择开始的节点必须是精确的节点,而不是父节点。在我们的例子中,我们试图将一些文本放入TextAngular控件,然后选择看起来像的文本,这样用户就可以“填充空白”

我们输入的是html的顺序
一些文本在这里:\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

<p>Some partial goes here
<ul>
    <li>Option 1</li>
    <li>_____</li>
</ul>

当问题是他们只是在看错误的节点时。

谢谢,但我也需要能够跨元素边界进行选择。我所说的“任意性”并不是指随机性。我确切地知道选择应该从哪里开始和结束,一直到字符偏移量。感谢您在此处发布:)
function find_(node) {
    var i, n;
    // return the node with the _'s
    for(i=0; i < node.childNodes.length; ++i) {
        n = node.childNodes[i];
        console.debug(n);
        if(n.textContent) {
            console.debug(n, n.textContent);
            if(n.textContent.search(/___+/) > 0) {
                return n;
            }
        }
        if(n.childNodes) {
            console.debug(n, n.childNodes);
            n = find_(n);
            if(n) {
                return n;
            }
        }
    }
    return null;
}
IndexSizeError: Failed to execute 'setStart' on 'Range': There is no child at offset 65.