zoukankan      html  css  js  c++  java
  • JS向光标指定位置插入内容

    方法:

    function insertHtmlAtCaret(html) {
    var sel, range;
    if (window.getSelection) {
    // IE9 and non-IE
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
    range = sel.getRangeAt(0);
    range.deleteContents();
    // Range.createContextualFragment() would be useful here but is
    // non-standard and not supported in all browsers (IE9, for one)
    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);
    // Preserve the selection
    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);
    }
    }

    调用方式:
    var content = '你好啊,我是新插入的内容数据';
    $('.js_content').focus();//要插入内容的div
    insertHtmlAtCaret(content)
  • 相关阅读:
    k近邻算法
    密码技术小总结
    编码的简单总结
    icmp dos和arp dos 攻击模拟实验
    WPA简单抓包分析
    Iptables实验
    Rabin简单加解密
    response响应数据
    浮动——小米手机案例
    ServletRequest请求详解
  • 原文地址:https://www.cnblogs.com/myphper/p/5319073.html
Copyright © 2011-2022 走看看