我想将剪贴板内容粘贴到 html 页面上。内容是从 ms-word 文件复制的。包含文字和图像。考虑以下代码:
<div id="pasteArea" contenteditable="True"></div>
<script type="text/javascript">
var pasteArea = document.getElementById('pasteArea');
pasteArea.onpaste = function (event) {
event.preventDefault();
event.stopPropagation();
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
for (index in items) {
var item = items[index];
if(item.kind === 'string'){
console.log(item.getData('text'));
// Getting the error in here!
}
else if(item.kind === 'file'){
// Code for handling images
}
}
}
</script>
我尝试使用 event.clipboardData.getData('text');
但它会获取整个文本(即跳过中间的图像),并且文本格式也会丢失。
您知道如何处理上述情况吗?谢谢。
最佳答案
您正在寻找需要回调来处理剪贴板的 getAsString。
https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem/getAsString
const pasteArea = document.getElementById('pasteArea');
pasteArea.onpaste = event => {
event.preventDefault();
const { items } = event.clipboardData;
for (const item of items) processClipboard(item)
}
const processClipboard = item => {
if (item.kind === 'string' && item.type === 'text/plain') {
item.getAsString(s => console.log(s))
}
}
div { background-color: #ccc; }
<div id="pasteArea" contenteditable="True">Paste something here</div>
关于javascript - 未捕获的 TypeError : item. getData 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54944973/