2017-10-13 72 views
1

当用户在移动Safari中粘贴图片时,我需要添加其他行为。 我用下面的代码获取clipboardDataSafari ClipboardEvent.clipboardData检查图片是否粘贴

document.getElementById('content').addEventListener('paste', function(e) { 
    var clipboardData = e.clipboardData; 
// check if image were pasted 
} 

从这一点来说,我怎么能检查是图像(JPG,PNG,GIF)进行粘贴或不?

回答

1

我无法从e.clipboardData中获取数据,因为它显示了所有数据。所以我使用Editable div来代替,然后您可以检查它是否是可编辑div内的图像,并查找其中的内容。

document.getElementById("content").addEventListener("paste", function(e) { 
 
    setTimeout(() => { 
 
    var pasted = $("#content").children(); 
 
    if (!pasted.length) { 
 
     console.log("nothing pasted!"); 
 
     return; 
 
    } 
 
    pasted.map((i, x) => { 
 
     if (x.tagName != "IMG") { 
 
     console.log(x); 
 
     console.log(`${x.tagName} not image`); 
 
     return; 
 
     } 
 
     console.log(`pasted image=[${x.src}]!`); 
 
    }); 
 
    }); 
 
});
#content { 
 
    width: 200px; 
 
    height: 200px; 
 
    border: 1px solid black; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id='content' contenteditable='true'></div>

当你data-url你可以电话jpgpng,如果不是会更加复杂,需要后端API