gpt4 book ai didi

javascript - 使用 setsrat 和 setEnd 选择部分文本

转载 作者:行者123 更新时间:2023-11-30 17:30:02 26 4
gpt4 key购买 nike

我正在尝试从这个 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);

最佳答案

jsBin demo

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com