Javascript:如何将多个p标签上的选定文本划分为每个标签的每个内容



我想知道沿着多个p标签的选定文本可以分为每个标签的每个内容。例如

<p>I am (selection start)a boy</p>
<p>You are(selection end) a girl</p>

我想像"一个男孩"和"你是"一样划分。

同样对于三个 p 标签,

<p>I am (selection start)a boy</p>
<p>You are a girl</p>
<p>We are(selection end) friends</p>

我想获得三个要素,"一个男孩","你是一个女孩","我们是"。

Chrome可以使用javascript吗?

提前感谢您的回答。

试试这个

document.onmouseup=function(){
var selected = document.getSelection().toString()
var data=selected.replace(/r?n|r/g, "n").split("n").filter(Boolean)
var dataWithSpan=data.map((x,y)=>`<span>${x}</span>`);
console.log(data)
console.log(dataWithSpan)
}
select from the following paragraps
<p>I am a boy</p>
<p>You are a girl</p>
select from the following paragraps
<p>I am a boy</p>
<p>You are a girl</p>
<p>We are friends</p>

最新更新