在contenteditable div中选择范围 [英] Select range in contenteditable div

查看:527
本文介绍了在contenteditable div中选择范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a contenteditable div and a few paragraphs in it.

这是我的代码:

<!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

Assuming, I want to make a range selection which will contain the string "world! This is"

怎么做?

推荐答案

一旦你抓住了包含要突出显示的文本的文本节点,很容易。你如何得到这些取决于你需要的通用性。就目前而言,在用户编辑之前,以下内容将起作用:

Once you've got hold of the text nodes containing the text you want highlighted, it's easy. How you get those depends on how generic you need this to be. As it is at the moment, before the user has edited it, the following will work:

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

这篇关于在contenteditable div中选择范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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