javascript - 在 contenteditable div 中选择范围

标签 javascript selection range

我有一个 contenteditable div 和其中的几个段落。

这是我的代码:

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body>
        <div id="main" contenteditable="true" 
             style="border:solid 1px black; width:300px; height:300px">
            <div>Hello world!</div>
            <div>
                <br>
            </div>
            <div>This is a paragraph</div>
        </div>
    </body>
</html>

假设,我想进行一个范围选择,其中将包含字符串“world!This is”

如何做到这一点?

最佳答案

一旦您掌握了包含要突出显示的文本的文本节点,就很容易了。如何获得这些取决于您需要它的通用性。目前,在用户编辑之前,以下操作将起作用:

var mainDiv = document.getElementById("main");
var startNode = mainDiv.firstChild.firstChild;
var endNode = mainDiv.childNodes[2].firstChild;

var range = document.createRange();
range.setStart(startNode, 6); // 6 is the offset of "world" within "Hello world"
range.setEnd(endNode, 7); // 7 is the length of "this is"
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);

关于javascript - 在 contenteditable div 中选择范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3771824/

相关文章:

javascript - 数组填充外部函数 - 不可访问的成员

mysql - 我如何限制MySQL中的选择?

WPF 数据网格选择问题

python - 在python中创建一个跨特定范围集的for循环函数

javascript - 释放鼠标时重置输入类型=范围

c# - 在 WebBrowser 中调用一个脚本,并等待它完成运行(同步)

javascript - 在 WebKit 中测量回流和绘制时间

javascript - 高效、干净的 JavaScript? JavaScript学习资源?

jquery - 使用tinyMCE.execCommand ('mceRemoveControl', false, "textarea_id"),Tinymce 和 j 为空;

c++ - C++11 中是否有一个范围类可用于基于范围的 for 循环?