img 图片相关
检测图片链接是否存在
function validateImage(src, cb) {
const img = new Image();
img.onload = () => {
const res = img.fileSize > 0 || (img.width > 0 && img.height > 0) ? true : false;
cb(res);
}
img.src = src;
}
validateImage('https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=709326223,3235457900&fm=26&gp=0.jpg', (res) => {
console.log(`图片是否存在: ${res}`);
});
设置兜底背景图
<div id="idname" class='classname' :style="handleImg(item.visual_img, 'idname')"></div>
.classname {
background-image: url('../images/default-img.png');
background-repeat: no-repeat;
background-position: center;
background-size: 100%;
}
async handleImg(imgUrl, domId) {
if (!imgUrl) return '';
const imgExit = await this.load(imgUrl).catch(() => false);
const domStyle = imgExit ? `url(${imgUrl})` : '';
document.querySelector(`#${domId}`).style.backgroundImage = domStyle;
},
load(imgUrl, minWidth = 1, minHeight = 1) {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
resolve(!!(img.fileSize > 0 || (img.width > minWidth && img.height > minHeight)));
};
img.onerror = () => {
resolve(false);
};
img.src = imgUrl;
});
},