我正在尝试从这个 fiddle 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);
最佳答案
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
https://developer.mozilla.org/en-US/docs/Web/API/range.setStart
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
关于javascript - 使用 setsrat 和 setEnd 选择部分文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23324302/