Javascript 在 contenteditable div 中选择范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3771824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select range in contenteditable div
提问by angry kiwi
I've got a contenteditablediv and a few paragraphs in it.
我有一个contenteditablediv 和几个段落。
Here's my code:
这是我的代码:
<!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>
Assuming, I want to make a range selection which will contain the string "world! This is"
假设,我想做一个范围选择,其中将包含字符串“world!This is”
How to do that?
怎么做?
回答by Tim Down
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);

