一直以来,对input的强大功能并没有做很深入的了解,平时也都是直接用第三方库实现对应的功能,现在需求中需要实现图片上传并控制大小与尺寸的要求。效果如下:
代码如下:
点我
/* 模拟上传 */ const btn = document.querySelector("#but") const ipt = document.querySelector("#ceshi") const sp = document.querySelector("p")
btn.onclick = function () {
ipt.click()
}
ipt.onchange = function (e) {
const file = e.target.files[0]
// 控制大小,这里根据需要自行设置
if (file.size>1024*10) {
alert("限制10Kb内图片上传")
return
}
const url = window.URL.createObjectURL(file);
const imgElement = new Image();
imgElement.onload = function () {
const {width,height} = this;
if ( width < 100 || height < 100 || width % height !== 0 ) {
alert("尺寸不符合,限制尺寸100*100");
return;
}
sp.innerHTML = file.name;
}
imgElement.src = url; // 注意这里给src地址赋值是需要写在imgElement.onload()方法后面的,由于onload()是回调一个函数,浏览器需要获取万这个图片信息后才可以拿到对应的宽高
}