[英]selecting partial text with setsrat and setEnd
I am trying to select the text some
from text in this fiddle http://jsfiddle.net/vZ2fF/ but it does not seem to be working at all... what am I doing wrong??? 我正在尝试从此小提琴http://jsfiddle.net/vZ2fF/中的文本中选择
some
文本,但它似乎根本不起作用...我在做什么错?
<div contenteditable="true">
<p id="ul1">
<span id="span1">some element</span>
<span>some element2</span>
</p>
</div>
var selection1= window.getSelection();
var range1=document.createRange();
var ul= document.getElementById("ul1");
var idspan=document.getElementById("span1");
range1.setStart(idspan, 0);
range1.setEnd(idspan, 5);
selection1.addRange(range1);
That is because, setEnd
's second argument endOffset
is the number of child nodes between the start of the endNode
. 这是因为
setEnd
的第二个参数endOffset
是endNode
起点之间的子节endNode
。
So, your idspan
has only one child node that is textnode
. 因此,您的
idspan
只有一个子节点,即textnode
。 So it will not work for range1.setEnd(idspan,5)
. 因此,它不适用于
range1.setEnd(idspan,5)
。 For that, you need to have 5 child elements. 为此,您需要有5个子元素。
This will work: range1.setEnd(idspan,1)
, since the number of child nodes in idspan
is just one (ie textnode). 这将起作用:
range1.setEnd(idspan,1)
,因为idspan
的子节点数仅为1(即textnode)。
var Win = window, Doc = document;
var selection1 = Win.getSelection ? Win.getSelection() : Doc.selection.createRange();
var range = Doc.createRange();
function El(id){ return Doc.getElementById(id); }
var ul = El("ul1");
var idspan = El("span1").firstChild; // Note the Node element
range.setStart(idspan, 0);
range.setEnd(idspan, 4);
selection1.addRange(range);
http://www.quirksmode.org/dom/range_intro.html http://www.quirksmode.org/dom/range_intro.html
https://developer.mozilla.org/en-US/docs/Web/API/range.setStart https://developer.mozilla.org/en-US/docs/Web/API/range.setStart
https://developer.mozilla.org/en-US/docs/Web/API/range.setEnd https://developer.mozilla.org/en-US/docs/Web/API/range.setEnd
https://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#dom-range-setstart https://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#dom-range-setstart
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.