[英]dom range.setStart / setEnd
I am trying to bold only the text hel
in this fiddle http://jsfiddle.net/yarkpakv/ but it does not seem to be working, what am I doing wrong??? 我试图在这个小提琴http://jsfiddle.net/yarkpakv/中只加粗文本hel
但它似乎没有起作用,我做错了什么?
var range = document.createRange(); var root_node = document.getElementById("test"); range.setStart(root_node,0); range.setEnd(root_node,3); var newNode = document.createElement("b"); range.surroundContents(newNode);
<div id="test"> <p>h</p>ello </div>
You need to visualize the DOM structure of your <div id="test">
element. 您需要可视化<div id="test">
元素的DOM结构。 It contains three children: 它包含三个孩子:
A text node that contains only white space. 仅包含空格的文本节点。
The <p>
element which contains a text node that has the value h
. <p>
元素,其中包含值为h
的文本节点。
A text node that has the value ello
. 具有值ello
文本节点。
So your range must start with the <p>
element and ends in the ello
text node, between the two l
characters. 因此,您的范围必须以<p>
元素开头,并以ello
文本节点结尾,在两个l
字符之间。 Therefore: 因此:
var range = document.createRange();
var root_node = document.getElementById("test");
// Start at the `<p>` element.
range.setStart(root_node, 1);
// End in the `ello` text node, between the two `l`s.
range.setEnd(root_node.childNodes[2], 2);
var newNode = document.createElement("b");
range.surroundContents(newNode);
Got it ... 得到它了 ...
var range = document.createRange();
var root_node = document.getElementById("test");
range.setStart(root_node.firstChild,0);
range.setEnd(root_node.firstChild,3);
var newNode = document.createElement("b");
range.surroundContents(newNode);
In all of the documentation, they are referencing the "Child" ... this solves that. 在所有文档中,他们引用了“Child”......这解决了这个问题。 In the case of your Fiddle, it will wrap the Letter "h" and the two <p>
and </p>
tags. 在你的小提琴的情况下,它将包装字母“h”和两个<p>
和</p>
标签。 Take them out and hel becomes bold. 把它们拿出去, hel变得大胆。
UPDATE : 更新 :
Apparently, whitespace will cause problems ... 显然,空白会引起问题......
HTML ... HTML ...
TEST 测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.