JSFiddle - React, Tailwind, and code Playground

by baofen14787

HTML

<div class="editor" id="js_editor" contenteditable="true" style="min-height:120px;border:#999 solid 1px;">直接粘贴图片到这!支持chrome、firefox浏览器!</div>

JavaScript

/**
     * 通过reader方式生成dataurl图片
     * @param event
     */
    function handlePaste(event) {
        var items = (event.clipboardData || event.originalEvent.clipboardData).items;
        console.log(JSON.stringify(items)); // will give you the mime types
        var blob = items[0].getAsFile();
        var reader = new FileReader();
        reader.onload = function(event){
            console.log(event.target.result)}; // data url!
        reader.readAsDataURL(blob);
    }

    /**
     * createObjectURL方式,创建图片文件
     * @param e
     */
    function handlePaste2(e) {
        var items = e.originalEvent.clipboardData.items;

        for (var i = 0; i < items.length; ++i) {
            console.log(items[i].type);
            if (items[i].kind == 'file' && items[i].type == 'image/png') {
                var blob = items[i].getAsFile();
                var img = document.createElement('img');
                img.src = window.URL? window.URL.createObjectURL(blob) : window.webkitURL.createObjectURL(blob);
                $("#js_editor").html(img);
            }
        }
    };

    $(function(){
        $("#js_editor").on("paste",handlePaste2)
    });