gpt4 book ai didi

javascript - 如何在html中查找选定的文本

转载 作者:行者123 更新时间:2023-12-03 12:17:38 26 4
gpt4 key购买 nike

如何在 div 中找到选定的文本,在 html

例如,我们在本文中选择了 5 到 11 :

     <div id="txt" >This is some <i> text </i> </div>

已选择:is some ,

但是在 html是:id="txt

如何找到它并在 <p> 之间替换或<span>还有其他标签可以避免丢失吗?

请原谅我的英语不好:)

最佳答案

演示:http://jsfiddle.net/dKaJ3/2/

function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
alert(html);
}

取自:How to replace selected text with html in a contenteditable element?

在提问之前尝试先找到东西;]

关于javascript - 如何在html中查找选定的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24605237/

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