zoukankan      html  css  js  c++  java
  • DIV 粘贴插入文本或者其他元素后,移动光标到最新处

    此文主要是可编辑div光标位置处理

    1:首先 设置一个可编辑的DIV,注意:设置 contenteditable="true" 才可以编辑DIV

     <div id="talkContent" style="resize: none;height:150px;overflow:auto" contenteditable="true"></div>

    2:移动光标js方法

    //聊天内容框 插入文本或者其他元素后,移动置光标到最新处
    function insertHtmlAtCaret(childElement) {
        var sel, range;
        if (window.getSelection) {
            // IE9 and non-IE
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();
    
                var el = document.createElement("div");
                el.appendChild(childElement);
                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);
        }
    }

    3:从光标现在的位置追加文本,成功后,光标在追加的文本后面

        insertHtmlAtCaret(document.createTextNode(‘这里是要追加的文本’));

    4:从光标现在的位置追加元素,成功后,光标在追加的元素后面

      var new_img = document.createElement('img');
        new_img.setAttribute('src', '这是图片地址');
        new_img.style.maxWidth = "200px";
        new_img.style.maxHeight = "120px";
        insertHtmlAtCaret(new_img);
  • 相关阅读:
    Canvas基础讲义
    封装一个DivTag
    递归深拷贝
    构造函数的执行过程
    封装一个Ajax工具函数
    数组去重
    [js开源组件开发]js多选日期控件
    自己写的表格插件autotable
    复杂表格的树形结构的添加删除行div实现
    自制html5塔防游戏
  • 原文地址:https://www.cnblogs.com/fj99/p/5499113.html
Copyright © 2011-2022 走看看