【问题标题】:Select range in contenteditable div在 contenteditable div 中选择范围
【发布时间】:2011-04-15 20:51:50
【问题描述】:

我有一个 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”的范围选择

怎么做?

【问题讨论】:

    标签: javascript selection range


    【解决方案1】:

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

    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);
    

    【讨论】:

    • removeAllRanges 然后addRange 是我在我的情况下缺少的部分。感谢您的代码!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多