效果图:
html部分
<div class="chose-pic-box">
<div class="show-pic">
<p class="upload-text">上传海报</p> <!-- 未上传时显示的文字提示 -->
<img src="../img/upload-pic.png" alt="" class="upload-icon"> <!-- 未上传时显示的提示图片 -->
<img src="" alt="" id="the-picture"> <!-- 上传的图片显示位置,起初为空或隐藏 -->
</div>
<input type="file" accept="image/jpg,image/jpeg,image/png,image/PNG" class="chose-pic-btn"
onchange="uploadPicture()"> <!-- 上传图片,在改变时调用显示图片的方法 -->
</div>
css部分
.chose-pic-box{
width: 200px;
height: 200px;
border: 1px solid lightgrey;
padding: 5px;
margin-left: 15px;
border-radius: 3px;
position: relative;
}
.chose-pic-btn{
width: 100%; /* 让其铺满整个框,点击框内任意地方都可以选择文件 */
height: 100%;
opacity: 0; /* 让其透明不显示,显示自己设置的样式 */
cursor: pointer;
position: absolute; /* 相对最外面的框位置固定 */
top: 5px;
left: 5px;
}
// 自己设置的样式
.show-pic{
width: 100%;
height: 100%;
border: 2px dashed lightgrey;
text-align: center;
font-size: 2.0rem;
color: #9d9d9d;
}
.show-pic .upload-text{
margin-top: 30px;
}
// 显示上传的图片,固定大小
.show-pic #the-picture{
display: inline-block;
width: 100%;
height: 100%;
}
js部分
function uploadPicture() {
var theFile = new FileReader();
var f = document.getElementsByClassName("chose-pic-btn")[0].files[0];
var thePic = document.getElementById("the-picture");
theFile.onload = function () {
thePic.src = this.result;
$(".upload-text").css("display", "none"); //隐藏未上传时的文字和图片
$(".upload-icon").css("display", "none");
};
if (f) {
theFile.readAsDataURL(f);
}
}
FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件,具体内容及使用方法可参考MDN文档。