码迷,mamicode.com
首页 > Web开发 > 详细

js 指定位置插入html标签(可编辑div)

时间:2016-07-14 13:26:52      阅读:640      评论:0      收藏:0      [点我收藏+]

标签:

demo效果如下:

技术分享

html代码部分如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>js获取编辑框游标的位置</title>
    <script src="http://www.w3school.com.cn/jquery/jquery-1.11.1.min.js" type="text/javascript"></script>
    
    <style type="text/css">
        #Div1, #Div2
        {
            width: 500px;
            height: 100px;
            border: solid 1px black;
        }
    </style>
</head>
<body>
<button type="button" id="ddddd" >
    插入字符
</button>
<div contentEditable="true" style="height:50px; border:2px solid red;" id="test">
dasdsadasdasdasd<img src="http://www.cnblogs.com/images/xml.gif" alt="订阅">dasdasdasdasdsadsa
</div>
 

</body>
</html>
<script>
$(#ddddd).click(function(){
    document.getElementById(test).focus(); 
    insertHtmlAtCaret(<img src="http://www.cnblogs.com/images/xml.gif" />);
})
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);
            }
        }
    } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(html);
    }
}
</script>

 

js 指定位置插入html标签(可编辑div)

标签:

原文地址:http://www.cnblogs.com/shizhouyu/p/5670031.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!