h5有两种方法可以实现图片的预览,即任意的图片到指定的区域,图片会显示出来。
第一种:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>
<style>
*{margin:0;padding:0;}
.pic{width:500px;
height:300px;
margin:50px auto;
background-color: cornflowerblue;
}
</style>
</head>
<body>
<div class="pic" draggable="true"></div>
<script>
var pic=document.getElementsByClassName('pic')[0];
pic.ondragover=function(e){//阻止默认事件
e.preventDefault();
e.stopPropagation();
return false;
}
pic.ondrop=function(e){
var file=e.dataTransfer.files[0];
console.log(file);
const read=new FileReader();
read.readAsDataURL(file);//读取图片路径
read.onload=function(e){
console.log(this.result);
if(/image/.test(this.result)){
const img=new Image();
img.src=this.result;
img.style.width="300px";
img.style.height="300px";
pic.appendChild(img);
}
}
e.preventDefault();//阻止默认事件
e.stopPropagation();
return false;
}
</script>
</body>
</html>
第二种是用Blob
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>
<style>
*{margin:0;padding:0;}
.pic{width:500px;
height:300px;
margin:50px auto;
background-color: cornflowerblue;
}
</style>
</head>
<body>
<div class="pic" draggable="true"></div>
<script>
var pic=document.getElementsByClassName('pic')[0];
pic.ondragover=function(e){
e.preventDefault();
e.stopPropagation();
return false;
}
pic.ondrop=function(e) {
var file = e.dataTransfer.files[0];
console.log(file);
//判断是否为图片
if (/image/.test(file.type)) {
const blob = new Blob([file]);
const url = window.URL.createObjectURL(blob);
console.log(url);
const img = new Image();
img.src = url;
img.style.width = '300px';
img.style.height = '300px';
img.onload = function () {
pic.appendChild(img);
}
e.preventDefault();
e.stopPropagation();
return false;
}
}
</script>
</body>
</html>