javascript - 浏览图像并插入 Iframe

标签 javascript html iframe

我想知道这是否可能。

我想创建一个函数来检索图像并将其插入到 iframe 中。用户必须能够选择一个文件(图像/视频)并将其插入到 iframe 中。

ma​​in.html

<input type="file" id="addImage">我已经用它来让用户选择一个文件。

<iframe class="frame" id="frame" src="insert.html"></iframe>这是 iframe 的。 iframe src 是另一个 html 文档。

insert.html

<span id="edit"></span>位于需要插入图像的 insert.html 中。

我不太明白如何使用 javascript 从用户选择中检索图像并将其插入到 iframe 中。

这可能吗?

最佳答案

是的,这是一个例子。关键是 Hook 到 iframe,然后使用它的 contentWindow .

EDIT

另外,我不知道你是指浏览文件还是拖放 API,所以我同时实现了这两个。

来自这些来源的大量帮助:

这是一个 fiddle :

JSFiddle

CSS

 *{
    font-family: Arial;
 }
 .section{
    width: 400px;
    padding: 20px;
    margin: auto;
 }
 #dragDiv{
    background-color: #ffffcc;
 }
 #browseDiv{
    background-color: #ccffcc;
 }
 #iframeDiv{
    background-color: #ffcccc;
 }
 #dropTarget{
    width: 300px;
    height: 300px;
    border-style: dashed;
    border-width: 5px;
 }
 .dropEnabled{
    border-color: #999999;
 }
 .dropEnabled:hover{
    border-color: #ff9933;
 }
 .dropMe{
    border-color: #99ff99;
 }

JS

 /**
  * I set up the listeners for dragging and dropping as well
  * as creating an iFrame for holding dragged in images
  * @returns {undefined}
  */
 function main() {
    // The div that receives drops and the new iFrame
    var targetDiv = document.getElementById("dropTarget"),
            iframe = document.createElement("iframe");

    // Set the iframe to a blank page
    iframe.src = "about:blank";

    // Append it to the target
    document.getElementById("iframeTarget").appendChild(iframe);

    // Drag over is when an object is hovering over the div
    // e.preventDefault keeps the page from changing
    targetDiv.addEventListener("dragover", function(e) {
       e.preventDefault();
       this.className = "dropMe";
    }, false);

    // Drag leave is when the object leaves the div but isn't dropped
    targetDiv.addEventListener("dragleave", function(e) {
       e.preventDefault();
       this.className = "dropEnabled";
    }, false);

    // Drop is when the click is released
    targetDiv.addEventListener("drop", function(e) {
       e.preventDefault();
       this.className = "dropEnabled";
       loadFile(e.dataTransfer.files[0], iframe);
    }, false);

    document.getElementById("upload").addEventListener("click", function() {
       var file = document.getElementById("browsedFile").files[0];
       loadFile(file, iframe);
    }, false);
 }

 /**
  * Load a file and then put it on an ifrmae
  * @param {Element} f The file that needs to get loaded
  * @param {Element} destination The iframe that the file is appended to
  * @returns {undefined}
  */
 function loadFile(f, destination) {
    // Make a file reader to interpret the file
    var reader = new FileReader();

    // When the reader is done reading,
    // Make a new image tag and append it to the iFrame
    reader.onload = function(event) {
       var newImage = document.createElement("img");
       newImage.src = event.target.result;
       destination.contentWindow.document.getElementsByTagName("body")[0].appendChild(newImage);
    };

    // Tell the reader to start reading asynchrounously
    reader.readAsDataURL(f);
 }

 // Run the main script
 window.onload = main;

HTML

<!DOCTYPE html>
<html>
   <head>
      <title>I framed it</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width">
   </head>
   <body>
      <div id="dragDiv" class="section">
         <div>The div below receives dragged in files</div>
         <div id="dropTarget" class="dropEnabled"></div>
      </div>
      <div id="browseDiv" class="section">
         <div>I upload stuff the boring way</div>
         <input type="file" id="browsedFile"><button id="upload">Upload</button>
      </div>
      <div id="iframeDiv" class="section">
         <div>And below me, an iFrame gets created</div>
         <div id="iframeTarget"></div>
      </div>
   </body>
</html>

结果如下:

enter image description here

还有 DOM:

enter image description here

EDIT

关于如何对视频执行此操作也发表了评论。有几种方法可以做到这一点,但这是我使用 HTML5 <vido> 来实现的一种方法。您可以在此处找到更多信息的标签:HTML Videos .

我敢肯定有一件棘手的事情是相当笨拙的,那就是如何说出您应该加载哪种文件。我用 switch()在文件的 type 上通常评估为类似以下内容的属性:image/pngvideo/mp4用于 MP4 视频。但是,这将您绑定(bind)到特定的文件格式。 一个更好的方法是制作一个正则表达式来判断它是只是一个图像还是一个视频并忽略格式,因为这个过程是粗鲁的这些类型的所有文件都相同。

我添加了自己的正则表达式实现。可能不是最好的,但它现在允许所有适当的图像类型通过。

此外,我尝试使用 Apple 的一些示例视频,可以在此处找到:Sample QuickTime Movies .但是,由于某些原因,这些方法不起作用。所以在那之后,我只是下载了 W3Schools 在他们的教程中使用的示例视频。我告诉您这一点是为了万一您尝试它但它不起作用,它可能是文件本身而不是您的代码。

已编辑 loadFile()功能

 /**
  * Load a file and then put it on an ifrmae
  * @param {Element} f The file that needs to get loaded
  * @param {Element} destination The iframe that the file is appended to
  * @returns {undefined}
  */
 function loadFile(f, destination) {
    // Make a file reader to interpret the file
    var reader = new FileReader(),
            loaderFunc = null,
            typeRegEx = /^(\w+)\//,
            contentType = f.type.match(typeRegEx)[1];

    // Figure out how to load the data
    switch (contentType) {
       case "video":
          loaderFunc = function(event) {
             var newVideo = document.createElement("video"),
                     newVideoSource = document.createElement("source");

             newVideo.width = 300;
             newVideo.height = 300;
             newVideo.setAttribute("controls");

             newVideoSource.src = event.target.result;
             newVideoSource.type = f.type;

             destination.contentWindow.document.getElementsByTagName("body")[0].appendChild(newVideo);
             newVideo.appendChild(newVideoSource);
          };
          break;
       case "image":
          loaderFunc = function(event) {
             var newImage = document.createElement("img");
             newImage.src = event.target.result;
             destination.contentWindow.document.getElementsByTagName("body")[0].appendChild(newImage);
          };
          break;
       default:
          console.log("Unknown file type");
          return;
    }

    // We should have returned, but just make sure
    if (loaderFunc) {
       // When the reader is done reading,
       // Make a new image tag and append it to the iFrame
       reader.onload = loaderFunc;

       // Tell the reader to start reading asynchrounously
       reader.readAsDataURL(f);
    }
 }

关于javascript - 浏览图像并插入 Iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20959737/

相关文章:

javascript - 如何中断表单发布,直到按下确认按钮?

javascript - 如何设置箭头键按顺序浏览 <img> 标签?

html - CSS:背景在移动设备上不拉伸(stretch)

javascript - Chrome 上 iframe 中的分页符不起作用?

php - 完成后使用 jQuery 向 iframe 反馈提交表单?

javascript - 如何将所有 javascript 编写在一个文件中?

php - 用js连接db并隐藏元素

javascript - Firefox 6 HTML audio.duration = NaN 问题

javascript - 页面不居中

javascript - 页面加载后在 React 中加载第三方 iframe,使 iframe 不影响 PageSpeed 得分