close

最近小編遇到一個需求,

就是要貼上前要把複製起來的內容加以處理,再貼回去

觀看一些技術網頁後,

記錄一下這邊寫法

Html 上面要加上

@paste="onContentPaste($event)"

 

 

onContentPaste: function(e) {
    // 宣吿 clipboardData
    var clipboardData = e.clipboardData || window.clipboardData;
    // 取得複製內容
    var pastedText = clipboardData.getData('Text');
    if(pastedText) {
        // 這邊是停止原本複製貼上流程
        e.stopPropagation();
        e.preventDefault();

        // 這邊可以方便加入一個 function 去處理複製內容  ex: this.pastedText = this.setPastedText(pastedText);
  
        // 將處理後的複製內容放回原位
        this.insertHtmlAtCursor(pastedText);
    }
},
insertHtmlAtCursor: function (embedHtml) {
    var sel, range, html;
    if (window.getSelection) {
        sel = window.getSelection();

        if (sel.getRangeAt && sel.rangeCount) {
            // 取得位子索引
            range = sel.getRangeAt(0);
            range.deleteContents();
            // 轉 Html 格式貼回對應位子
            range.insertNode(this.createHtmlNode(embedHtml));
        }
    } else if (document.selection && document.selection.createRange) {
        document.selection.createRange().text = embedHtml;
    }
},

createHtmlNode: function(htmlStr) {
    var frag = document.createDocumentFragment(),
        temp = document.createElement('div');
    temp.innerHTML = htmlStr;
    while (temp.firstChild) {
        frag.appendChild(temp.firstChild);
    }
    return frag;
},
arrow
arrow
    文章標籤
    vue clipboardData Paste
    全站熱搜

    妙筆丹青 發表在 痞客邦 留言(0) 人氣()