#pic{
position: absolute;
top: 0;
bottom: 0;right: 0;left: 0;
z-index: 10;display: none;
width: 1.5rem;
height: 1.5rem;border-radius: 0.06rpx;
}
.upload-box{
width: 1.5rem;
height: 1.5rem;
border-radius: 0.06rem;
background-color: #f2f2f2;
display: flex;flex-direction: column;
justify-content: center;align-items: center;position: relative;overflow: hidden;
}
.upload-box .add-icon{
width: 0.5rem;
height: 0.5rem;
}
.upload-box .add-text{
margin-top: 0.1rem;
font-size: 0.24rem;color: #808080;
}
<div class="upload-box" onclick="onChoseImg()">
<input class="upload" id="upload" type="file" accept="image/*" title="" />
<img src="./image/add.png" class="add-icon" />
<span class="add-text">添加图片</span>
<img id="pic" />
</div>
<script>
window.onload = function() {
var input = document.getElementById("upload");
//监听选择图片
input.addEventListener("change", function() {
if (input.files && input.files.length > 0) {
var imgPath = getObjectURL(input.files[0]);
var imgEl = document.getElementById("pic")
imgEl.src = imgPath;//预览图片
imgEl.style.display = "inline-block";
}
})
}
//获取本地图片url
function getObjectURL(file) {
var url = null;
if (window.createObjectURL != undefined) {
url = window.createObjectURL(file);
} else if (window.URL != undefined) {
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) {
url = window.webkitURL.createObjectURL(file);
}
return url;
}
//选择本地图片
function onChoseImg() {
var input = document.getElementById("upload");
input.click(); //模拟点击
}
//提交并上传图片
function sumbit() {
var formData = new FormData();
formData.append("file", document.getElementById("upload").files[0]);
$.ajax({
type: "post",
dataType: "json",
url: "https://xxxxxx.....",
data:formData,
processData: false,
contentType: false,
success: function(data) {
}
})
}
</script>
样式如下: