<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>apply</title>
<!-- 导入css文件 -->
<link rel="stylesheet" type="text/css" href="index.css">
<!-- 定义App端H5 -->
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
</head>
<body>
<div id="oDiv1">
<!-- 都做为背景图 -->
<label for="File1" style="display:block" id="Label1"></label>
<input id="File1" type="file" οnchange="func1(this)" style="display:none;" accept="image/jpeg,image/jpg,image/png">
<input id="oIn" type="text" placeholder="请输入姓名" maxlength="5">
<P id="Text1"></P>
</div>
<!-- 导入jq库 -->
<script src="./jquery-3.2.1.js"></script>
<!-- 导入js文件,放在html后面 -->
<script src="index.js"></script>
</body>
</html>
CSS部分
*{
list-style: none;
text-decoration: none;
padding: 0;
margin: 0;
}
::-webkit-input-placeholder { //给input若提示更改字体颜色
color: hotpink;
}
body{
background-image: url('../images/Bimg.jpg');
background-repeat: no-repeat;
background-size: 100%;
}
#Label1{
width:60%;
height: 250px;
display: block;
margin: 100px auto 0;
background-image: url('../images/520_uploading.jpg');
background-repeat: no-repeat;
background-size: 100% auto;
}
JS部分
if (typeof FileReader == 'undefined') {
document.getElementById("Text1").InnerHTML = "<h1>当前浏览器不支持FileReader接口</h1>";
}
//选择图片,马上预览
function func1(obj) {
var file = obj.files[0];
console.log(obj);
console.log(file);
console.log("file.size = " + (file.size / 1024).toFixed(2) + "M"); //file.size 单位为byte
// alert("file.size = " + (file.size/1024).toFixed(2) + "M");
var reader =new FileReader();
//读取文件过程方法
reader.onloadstart = function (e) {
console.log("开始读取....");
}
reader.onprogress = function (e) {
console.log("正在读取中....");
}
reader.onabort = function (e) {
console.log("中断读取....");
}
reader.onerror = function (e) {
console.log("读取异常....");
}
reader.onload = function (e) {
console.log("成功读取....");
$("#Label1").css({ "backgroundImage": "url(" + e.target.result + ")" });
}
reader.readAsDataURL(file); //把选择的图片文件调用readAsDataURL方法,把图片数据转成base64字符串形式显示在页面上
}
![](https://i-blog.csdnimg.cn/blog_migrate/151ba14151f098620173955cea648fd6.png)