jQuery-在光标定位的地方插入文字的插件

33次阅读

共计 1100 个字符,预计需要花费 3 分钟才能阅读完成。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery 在光标定位的中央插入文字的插件 </title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head> 
<body> 
<p><button onclick="getSelectionCoords()"> 点击 </button></p>
<div class="js_content" contentEditable="true"> 在光标定位的中央插入文字 </div>
<script>
function insertHtmlAtCaret(html) {
    var sel, range;
    if (window.getSelection) {sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {range = sel.getRangeAt(0);
            range.deleteContents();
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ((node = el.firstChild)) {lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);
            if (lastNode) {range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    }
    if (document.selection && document.selection.type != "Control") {document.selection.createRange().pasteHTML(html);
    }
}
function getSelectionCoords() {
    var content = '<span contentEditable="false"> 你好啊!</span>'
    $('.js_content').focus() 
    insertHtmlAtCaret(content)
}
</script>
</body>
</html>

以上内容均摘自网络,
浏览器反对状况:chrome 齐全反对,

正文完
 0