關(guān)于div標(biāo)簽可編輯且插入其它標(biāo)簽的問題

落花有意隨流水,流水無心蝶戀花

最近在做一個類似下面的功能:

1576576638695.jpg

由于textarea不能滿足該要求,所以只有通過div來實現(xiàn),由于時間關(guān)系就不在這里啰嗦了,直接上代碼

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <%@include file="/common/common.jsp" %>
    <style type="text/css">
        h3{margin-bottom:10px;margin-top: 20px;}
        .tip{color:grey;font-style: italic;margin-left: 20px;}
    </style>
</head>
<body>
<div class="page">
    <div class="page-content">
        <h3>標(biāo)準(zhǔn)按鈕</h3>
        <button class="ui-button ui-button-primary mr-2">按鈕</button>
        <button class="ui-button ui-button-success mr-2">按鈕</button>
        <button class="ui-button ui-button-warning mr-2">按鈕</button>
        <button id="sendEmoji" class="ui-button ui-button-error mr-2">添加標(biāo)簽按鈕</button>
    </div>

    <div id="editor"  placeholder="請輸入您的內(nèi)容" contenteditable="true"
         style="overflow-y:scroll;width: 500px;height: 300px;margin-left: 100px; line-height: 20px">

    </div>
</div>
<script type="text/javascript">

    var inputResizeDom;
    var edit = document.getElementById('editor')
    var sendEmoji = document.getElementById('sendEmoji')

    // 定義最后光標(biāo)對象
    var lastEditRange;

    // 編輯框點擊事件
    edit.onclick = function() {
        // 獲取選定對象
        var selection = getSelection()
        // 設(shè)置最后光標(biāo)對象
        lastEditRange = selection.getRangeAt(0)
    }

    // 編輯框按鍵彈起事件
    edit.onkeyup = function() {
        // 獲取選定對象
        var selection = getSelection()
        // 設(shè)置最后光標(biāo)對象
        lastEditRange = selection.getRangeAt(0)
    }

/* 此處代碼可以屏蔽掉,這是每次插入后定位到末尾的代碼
    editor.onfocus = function () {
        window.setTimeout(function () {
            var sel,range;
            if (window.getSelection && document.createRange) {
                range = document.createRange();
                range.selectNodeContents(editor);
                range.collapse(true);
                range.setEnd(editor, editor.childNodes.length);
                range.setStart(editor, editor.childNodes.length);
                sel = window.getSelection();
                sel.removeAllRanges();
                sel.addRange(range);
            } else if (document.body.createTextRange) {
                range = document.body.createTextRange();
                range.moveToElementText(editor);
                range.collapse(true);
                range.select();
            }
        }, 1);
    }
*/
    // 表情點擊事件
    sendEmoji.onclick = function() {
        insertAtCursorDiv(edit,"添加標(biāo)簽按鈕");
    }

    //插入標(biāo)簽
    function insertAtCursorDiv(myField, myValue) {
        // 編輯框設(shè)置焦點
        myField.focus()
        // 獲取選定對象
        var selection = window.getSelection();//getSelection()
        // 判斷是否有最后光標(biāo)對象存在
        if (lastEditRange) {
            // 存在最后光標(biāo)對象,選定對象清除所有光標(biāo)并添加最后光標(biāo)還原之前的狀態(tài)
            selection.removeAllRanges()
            selection.addRange(lastEditRange)
        }

        var emojiText = document.createElement("input")
        emojiText.setAttribute("value", "標(biāo)簽的文字");
        emojiText.setAttribute("data-code", "123");
        emojiText.setAttribute("disabled", 'true');
        emojiText.style.width = input_resize("標(biāo)簽的文字") + 'px';
        emojiText.style.background = 'lightskyblue';
        emojiText.style.borderRadius = '10px';
        emojiText.style.textAlignLast = 'center';
        emojiText.style.font = '16px';

        insertHtmlAtCaret(emojiText.outerHTML);
        // 無論如何都要記錄最后光標(biāo)對象
        lastEditRange = selection.getRangeAt(0)
    }

    var modalVm = avalon.define({
        $id:'inputLabel',

    });

    componentDidMount();

    function componentDidMount(){
        //增加隱藏節(jié)點,編輯模板時計算標(biāo)簽寬度
        if($('.hidden').length < 1){
            inputResizeDom = document.createElement('span');
            inputResizeDom.setAttribute('class', 'hide-dom');
            document.getElementsByTagName('body')[0].appendChild(inputResizeDom);
        }
    }

    function input_resize(html) {
        inputResizeDom.innerHTML = html;
        inputResizeDom.style.fontSize = '16px';
        return inputResizeDom.getBoundingClientRect().width.toFixed(4);
    }


    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("input");

                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") {
            document.selection.createRange().pasteHTML(html);
        }
    }
</script>
</body>
</html>

這是一個比較全的代碼,當(dāng)然還是有參考文章的
js之向div contenteditable光標(biāo)位置添加字符
js-處理div設(shè)置的編輯框處理焦點定位追加內(nèi)容

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容