以下代码来自专门用于在 imgur.com 上传图片的页面。这是网络上的模型,你可以 pc 白色拖放图片没问题。我的问题是:我需要添加哪些代码才能从其他浏览器拖放图像?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
<title>Upload</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>.
<style>
body {text-align: center; padding-top: 100px;}
div { border: 10px solid black; text-align: center; line-height: 100px; width: 200px; margin: auto; font-size: 40px; display: inline-block;}
#link, p , div {display: none}
div {display: inline-block;}
.uploading div {display: none}
.uploaded div {display: none}
.uploading p {display: inline}
.uploaded #link {display: inline}
</style>
<script>
window.ondragover = function(e) {e.preventDefault()}
window.ondrop = function(e) {e.preventDefault(); upload(e.dataTransfer.files[0]); }
function upload(file) {
if (!file || !file.type.match(/image.*/)) return;
document.body.className = "uploading";
var fd = new FormData();
fd.append("image", file);
fd.append("key", "myapicode");
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://api.imgur.com/2/upload.json");
xhr.onload = function() {
document.querySelector("#link").href = JSON.parse(xhr.responseText).upload.links.imgur_page;
var test = JSON.parse(xhr.responseText).upload.links.imgur_page;
var dataString = 'content=' + test + '&page=something';
$.ajax({
type: "POST",
url: "upload.img.php",
data: dataString,
cache: false,
success: function(html){
}
});
document.body.className = "uploaded";
}
xhr.send(fd);
}
</script>
</head>
<body>
<div>DROP!<button onclick="document.querySelector('input').click()">Or click</button></div>
<input style="visibility:collapse;width:0px;" type="file" onchange="upload(this.files[0])">
<p>Uploading...</p>
<a id="link">Its online!!!</a>
</body>
</html>
答案 0 :(得分:1)
并非所有浏览器都支持此功能,但Firefox会允许您将图像从浏览器拖到另一个浏览器或计算机,而Chrome则不允许您将图像拖出浏览器。
此page有一个所谓的dropzone,在Chrome中打开并在Firefox中打开图像,您可以将图像直接从Firefox拖动到Chrome,但它似乎没有相反的方式。
script评论很好,应该给你一些想法,拖放的内容基本上设置如下:
var dropzone;
dropzone = document.getElementById("dropzone");
dropzone.addEventListener("dragenter", dragin, false);
dropzone.addEventListener("dragleave", dragout, false);
dropzone.addEventListener("dragover", stopPropagation, false);
dropzone.addEventListener("drop", drop, false);
dragin
,dragout
,drop
等是在脚本中找到的那些事件上调用的函数。