【问题标题】:how to find selected text in html如何在html中找到选定的文本
【发布时间】:2014-07-07 07:35:46
【问题描述】:

如何在 divhtml 中找到选定的文本

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

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

已选择:is some

但在html 中是:id="txt

如何找到这个并在&lt;p&gt;&lt;span&gt;之间替换其他标签以避免丢失?

对不起,我的英语不好:)

【问题讨论】:

  • 请添加产生id="txt的代码。
  • 这不是代码。它刚刚在 html 中从 5 到 11 中选择...

标签: javascript html text selection


【解决方案1】:

演示: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?

在你问之前试着找到东西;]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-20
    • 2010-10-11
    • 2011-03-26
    • 1970-01-01
    • 2019-07-10
    • 2018-05-06
    • 2010-11-11
    • 1970-01-01
    相关资源
    最近更新 更多