<div id="input_img_father_div"> <!--设置input的position为absolute,使其不按文档流排版,并设置其包裹整个布局 --> <!-- 设置opactity为0,使input变透明 --> <!-- 只接受jpg,gif和png格式 --> <input id="upload_input" type="file" accept="image/*"/> <!-- 自定义按钮效果 --> <div id="input_img_btn_div"> <span id="input_img_btn_span">上传图片:</span> <img id="upload" src="./upload.png" style=" 40px; height: 40px; vertical-align: middle;"/> </div> </div> </div>
css文件:
#input_img_father_div { position: relative; width: 170px; height: 200px; vertical-align: middle; opacity: 60; background-color: #c6c6c6; display: flex; /*flex弹性布局*/ justify-content: center; align-items: center; } #upload_input { position: absolute; top: 0; bottom: 0; left: 0; right: 0; opacity: 0; width: 170px; height: 200px; } #input_img_btn_div { text-align: center; display: flex; flex-direction: column; /*元素的排列方向为垂直*/ justify-content: center; /*水平居中对齐*/ align-items: center; /*垂直居中对齐*/ } #input_img_btn_span { font-size: 24px; vertical-align: middle; } img#upload { width: 170px; height: 200px; }
实现图片预览:
{# 图片预览 #} <script> {# 上传样板图片预览 #} $("#upload_input").change(function () { var objUrl = getObjectURL(this.files[0]);//获取文件信息 console.log(objUrl) if (objUrl) { $('span#input_img_btn_span').hide(); $('img#upload').show(); $("img#upload").attr("src", objUrl); } }); function getObjectURL(file) { var url = null; if (window.createObjectURL != undefined) { url = window.createObjectURL(file); } else if (window.URL != undefined) { // mozilla(firefox) url = window.URL.createObjectURL(file); } else if (window.webkitURL != undefined) { // webkit or chrome url = window.webkitURL.createObjectURL(file); } return url; } </script>
最终效果:
上传前: 上传后: