首页 > 解决方案 > 仅在特定 div 中替换选定的 HTML

问题描述

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

我想要做的是复制选定的 HTML,将标签包裹起来,然后用它替换选择。因此,例如,“测试”将变为“测试”。

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

标签: javascripthtmlgetselection

解决方案


嗨,在选定的 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>

希望这可以帮助。


推荐阅读