Content table inserts and pastes plain text content

This article mainly introduces how to insert the input content at the cursor position or paste the plain text content at the cursor position when the div tag is set to contentable = 'true'. For the knowledge involved, please refer to the following: http://www.zhangxinxu.com/wordpress/2016/01/contentable-plaintext-only/

http://www.jb51.net/article/57650.htm 

https://www.cnblogs.com/rainman/archive/2011/02/27/1966482.html

http://www.zhangxinxu.com/wordpress/2011/04/js-range-html%E6%96%87%E6%A1%A3%E6%96%87%E5%AD%97%E5%86%85%E5%AE%B9%E9%80%89%E4%B8%AD%E3%80%81%E5%BA%93%E5%8F%8A%E5%BA%94%E7%94%A8%E4%BB%8B%E7%BB%8D/

http://kjah.iteye.com/blog/422509

First, set up html, a button for insert operation, and a div to implement contentable function and main logic

<button type="button" id='insert'>Insert title</button>
<div contentEditable="true" id="editor">
    <h3>Subheading</h3>
    <p>text</p>
</div>

Next is the realization of js logic function

document.getElementById('insert').onclick=function(){
    // When clicking the insert button, the system pop-up box will input the content
    var content = prompt('Please enter content');

    // To prevent clicking when the edit box does not get the focus, add an operation to make the edit box get the focus
    document.getElementById('editor').focus();

    // Execute insert method
    if(!!content){
        insertHtml('<h4>'+content+'</h4>');
    }
}

The main logic is in the insertHtml method

function insertHtmlAtCaret(html) {
    //Selection Object representing the text range or the current position of the cursor selected by the user.
    //In Africa IE Browser ( Firefox,Safari,Chrome,Opera)You can use window.getSelection()Get selection object
    //anchor Select the start point for the area.
    //focus End point of the selected area.
    //range It is a kind of fragment(HTML Fragment),It contains a part of a node or text node. Generally, there is only one page at the same time range,It could be multiple range(Use Ctrl Click to select multiple, but some browsers do not allow it, such as Chrome). Can from selection Get in range Object, you can also use document.createRange()Method.
    var sel = window.getSelection(), 
        range;

    if (sel.getRangeAt && sel.rangeCount) {
        //getRangeAt(index) From the present selection Object to get a range Object.
        range = sel.getRangeAt(0);
        //deleteContents()Method,range Content will be deleted
        range.deleteContents();
        //Write and load the input to dom in
        var el = document.createElement("div");
        el.innerHTML = html;
        var frag = document.createDocumentFragment(), node, lastNode;
        while ( (node = el.firstChild) ) {
            lastNode = frag.appendChild(node);
        }
        //insertNode,stay range Insert a node at the beginning of
        range.insertNode(frag);
        //Ending
        if (lastNode) {
            range = range.cloneRange();
            range.setStartAfter(lastNode);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
    
}

At this time, paste the content into the edit box with the original style. Obviously, it is not the result we want, so we need to change the pasted text

document.getElementById('editor').onpaste=function(event){
    var e = event || window.event
    // Block default paste
    e.preventDefault();
    // Paste event has one clipboardData Provides access to the clipboard
    // clipboardData Of getData(fomat) Get data in the specified format from the clipboard
    var text =  (e.originalEvent || e).clipboardData.getData('text/plain') || prompt('Enter text here');
    // insert
    document.execCommand("insertText", false, text);
};

Complete code is attached

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>contenteditable</title>
    <style>
        #insert{
            width: 90px;
            height: 30px;
            border: 1px solid #ccc;
            background-color: #fff;
            margin: 10px;
        }
        #editor{
            padding: 10px;
            overflow-y: auto;
            min-height:200px; 
            border:1px solid #f33;
            outline: 0;
        }
        #editor h4{
            margin: 10px 0;
        }
    </style>
</head>
<body>

<button type="button" id='insert'>Insert title</button>
<div contentEditable="true" id="editor">
    <h3>Subheading</h3>
    <p>text</p>
</div>
    
</body>
<script>

document.getElementById('insert').onclick=function(){
    var content = prompt('Please enter content');
    document.getElementById('editor').focus();
    if(!!content){
        insertHtmlAtCaret('<h4>'+content+'</h4>');
    }
}

document.getElementById('editor').onpaste=function(event){
    var e = event || window.event
    e.preventDefault();
    var text =  (e.originalEvent || e).clipboardData.getData('text/plain') || prompt('Enter text here');

    document.execCommand("insertText", false, text);
};

function insertHtmlAtCaret(html) {
    var sel = window.getSelection(), 
        range;

    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);
        }
    }
}
</script>
</html>

Tags: Javascript Fragment IE Firefox

Posted on Tue, 31 Mar 2020 07:41:25 -0700 by freakonaleash