Да, вот пример. Ключ должен подключиться к iframe, а затем использовать его contentWindow
.
EDIT
Кроме того, я не знаю, если вы имели в виду на просматривание для файла или drag'n'drop API, так я реализовал оба.
Много помощи из этих источников:
И вот сценарий:
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>
И вот результат:
И DOM:
EDIT
Было сделано замечание о том, как сделать это с помощью видео, а также. Есть несколько способов сделать это, но вот один из способов сделать это с помощью тега HTML5 <vido>
, который можно найти здесь: HTML Videos.
Одна сложная вещь, которая, я уверен, довольно неуклюжна, - это сказать, какой файл вы должны загружать. Я использую switch()
в атрибуте файла type
, который обычно имеет значение: image/png
или video/mp4
для видеороликов MP4. Однако это связывает вас с конкретным файловым форматом.
Лучшим способом сделать это было бы сделать регулярное выражение, которое определяет, является ли
изображением или видео и игнорирует формат, так как процесс
rougly тот же самый для всех файлов этих типов.
Я добавил свое собственное регулярное выражение. Наверное, это не самое лучшее, но теперь он позволяет всем подходящим типам изображений.
Кроме того, я попытался использовать некоторые примеры видео от 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);
}
}
Спасибо, но я хотел бы, чтобы пользователь сам выбрал свое изображение, поэтому я использовал тег . так как я могу получить их изображение и вставить в iframe? –
@User Хорошо, попробуйте это. Он использует как '', так и API перетаскивания в HTML5. – zero298
Спасибо, что сейчас я тестирую его. Кажется, это работает на JSFiddle, хотя я пытался использовать его в IE и Chrome. В JS появляется ошибка, которая вызывает всплытие Ошибка выполнения JavaScript JavaScript: невозможно получить свойство addEventListener свойства неопределенной или нулевой ссылки. –