dom range.setStart / setEnd(dom range.setStart/setEnd)
问题描述
我试图在这个小提琴 http://jsfiddle 中只加粗文本 hel
.net/yarkpakv/ 但它似乎没有工作,我做错了什么???
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???
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>
推荐答案
您需要可视化 <div id="test">
元素的 DOM 结构.它包含三个孩子:
You need to visualize the DOM structure of your <div id="test">
element. It contains three children:
仅包含空格的文本节点.
A text node that contains only white space.
<p>
元素包含一个值为 h
的文本节点.
The <p>
element which contains a text node that has the value h
.
具有 ello
值的文本节点.
A text node that has the value ello
.
因此,您的范围必须以 <p>
元素开始,并在两个 l
字符之间的 ello
文本节点结束.因此:
So your range must start with the <p>
element and ends in the ello
text node, between the two l
characters. 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);
这是一个小提琴.
这篇关于dom range.setStart/setEnd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:dom range.setStart/setEnd


- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01