我有一个 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/