【问题标题】:Replace selected HTML only in a specific div仅在特定 div 中替换选定的 HTML
【发布时间】:2023-03-21 05:52:01
【问题描述】:

我想选择用户在 contenteditable div 中选择的任何内容的 HTML。我找到了一些代码来检索所选内容的 HTML,但它不仅限于 div。

我想要做的是复制选定的 HTML,将标签包裹在它周围,然后用它替换选择。因此,例如,'test' 会变成 'test'。

<div contenteditable="true" class="body" id="bodydiv"></div>

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;
        }
    }
}

【问题讨论】:

  • 感谢您的回复。我已经看到了。唯一的问题是它适用于您选择的任何文本,包括 div 之外的内容。

标签: javascript html getselection


【解决方案1】:

您好,用于在选定的 div 中获取内容(文本)我创建了一个小代码,您可以查看它是否适合您:

$(document).ready(function(){
         $(document).bind('mouseup', function(){
         var content =  getSelected();
            content = "<b>"+content+"</b>";
            $('#selected').html(content);
        });
});

    function getSelected(){
        var t;
        if(window.getSelection){
           t = window.getSelection();
           var start = t.focusOffset;
           var end = t.baseOffset;
           t = t.anchorNode.data;
           t = t.slice(start, end);
        }  else if (document.selection) {
             t = document.selection.createRange().text;
        }
        return t;
    }

还有

<div id="selected"></div>

希望这会有所帮助。

【讨论】:

  • 感谢您的回复。该代码似乎只捕获选择之后的任何内容。
  • 此外,它似乎正在捕获页面上的任何选择,而不仅仅是在 div 中。
  • 您只想选择文本并在其上运行函数在任何 div 中?
  • 抱歉回复晚了。是的,请。
猜你喜欢
  • 1970-01-01
  • 2012-04-13
  • 1970-01-01
  • 2011-04-29
  • 2022-07-12
  • 2012-04-07
  • 2015-08-15
  • 1970-01-01
  • 2011-12-24
相关资源
最近更新 更多