使用<input type="file">和JS实现上传图片操作。
1.先写出css样式,这里采用了响应式布局,写的移动端样式。
<style>
* {
padding: 0;
margin: 0;
list-style: none;
}
html {
font-size: 62.5%;
}
body {
text-align: center;
}
.alert {
padding-top: 60px;
font-size: 2.4rem;
display: none;
}
.container {
height: 100vh;
background-color: deepskyblue;
overflow: hidden;
}
@media screen and (min-width:968px) {
/* 非移动端 */
.alert {
display: block;
}
.container {
display: none;
}
}
.head_pic {
width: 100px;
height: 100px;
margin: 80px auto;
border-radius: 50%;
/* 插入一张默认图片 */
background-image: url(https://img0.baidu.com/it/u=3822250181,2054335924&fm=253&fmt=auto&app=120&f=JPEG?w=750&h=500);
background-size: cover;
background-position: center center;
}
input {
display: block;
width: 100px;
height: 100px;
/* 隐藏上传文件的框,点击图片时仍可上传 */
opacity: 0;
}
</style>
2.html样式
<p class="alert">请使用移动端打开</p>
<div class="container">
<div class="head_pic">
<input type="file">
</div>
</div>
3.js实现上传图片操作
<script>
//获取input
var ipt = document.querySelector("input");
//获取图片显示区域
var dHeadPic = document.querySelector(".head_pic");
//onchange事件,事件会在域的内容改变时发生
ipt.onchange = function (e) {
//选择的图片
var file = this.files[0];
//创建一个文件读取对象
var reader = new FileReader();
//onload 事件会在页面或图像加载完成后立即发生。
reader.onload = function () {
//读取完成后执行
// reader.result读取文件的信息内容
dHeadPic.style.backgroundImage = `url(${reader.result})`;
}
//调用函数
reader.readAsDataURL(file);
}
这样一个图片上传操作就完成了。