首页 > 解决方案 > 将屏幕截图粘贴到的适当 html5 输入占位符是什么?

问题描述

我想添加一个输入框(占位符),用户可以将屏幕截图粘贴到其中。img 不会这样做,因为它需要将屏幕截图保存到图像文件中,然后将 scr 定向到它。太麻烦了。我想要一个简单的副本(或打印屏幕)并粘贴。

我修改了以下讨论中的代码: HTML Paste Clipboard Image to File Input,但它不起作用。

<form id="new_document_attachment" method="post">
        <div class="actions"><input type="submit" name="commit" value="Submit" /></div>
        <img src="" alt="Screen Shot" id="image_attachment_doc">
</form>
<script>
    const form = document.getElementById("new_document_attachment");
    const imageInput = document.getElementById("image_attachment_doc");

    imageInput.addEventListener('change', () => {
    form.submit();
    });

    window.addEventListener('paste', e => {
    imageInput.src = e.clipboardData.files;});
</script>

标签: html

解决方案


您需要将 File 对象中的图像数据转换为 Data URL。
感谢Loading an image to a <img> from <input file>

您的示例也有一点限制,因为虽然图像会显示,但页面几乎会立即重新加载。

在下面的示例中,未提交表单。

const log = document.getElementById("log");

window.addEventListener('paste', e => {
  var files = e.clipboardData.files;
  
  //Put the file into an input so it will be included with the form submit
  document.getElementById("files").files = files;
  
  //This won't work because the src holds a string
  //and the file object becomes serialized into "[object%20File]"
  //This can be seen in the console
  document.getElementById("img").src = files[0];
  
  //Show image by loading it as an DataURL
  var fr = new FileReader();
  fr.onload = function() {
    document.getElementById("img").src = fr.result;
  }
  fr.readAsDataURL(files[0]);
});
<form id="form" method="post">
  <img id="img" alt="Screen Shot">
  <input type="file" name="files" id="files" />
  <input type="submit" />
</form>

<p>Press Ctrl+V to paste an image into this window</p>


推荐阅读