携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第9天,点击查看活动详情
js 获取图片原始尺寸
方法一: 使用图片的属性 naturalWidth
width 和 height,是图片当前显示的宽和高,naturalWidth 和 naturalHeight,是图片的实际的宽度高度。
如果css里设置了宽高,
el.style.width
即可取到当前img宽高 在图片onload加载成功后获取。
<img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/729e29c8adce46ff959150897cf911c1~tplv-k3u1fbpfcp-zoom-1.image" style="width: 50px;" onload="getSize(this)">
function getSize(event) {
console.log(event.width, event.height);
console.log(event.naturalWidth, event.naturalHeight);
}
浏览器兼容情况:
方法二:
构造 Image 对象,不指定宽和高,width 和 height 就是图片的真实大小。 兼容性比naturalWidth更好。 这里创造的Image对象不一定要添加到 DOM 中。
var temImg = new Image();
temImg.src = “https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/729e29c8adce46ff959150897cf911c1~tplv-k3u1fbpfcp-zoom-1.image”
temImg.onload = function() {
console.log("实际尺寸:", temImg.width, temImg.height);
}
结合上述两种方法食用更佳:
function getImgNatural(img, callback) {
if (typeof img.naturalWidth == "undefined") { // IE6/7/8
var temImg = new Image();
temImg.onload = ``function``() {
callback({width: temImg.width, height:temImg.height});
}
temImg.src = img.src;
} else{ // 支持H5的现代浏览器
callback({width: img.naturalWidth, height:img.naturalHeight});
}
}
var img = document.getElementById('myImage');
console.log("显示尺寸:", img.width, img.height);
getImgNatural(img,function(dimension){
console.log("实际尺寸:", dimension.width, dimension.height);
});
js判断img是否加载完成
图片load方法
<img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/729e29c8adce46ff959150897cf911c1~tplv-k3u1fbpfcp-zoom-1.image" style="width: 50px;" onload="handleOnload(this)">
function handleOnload(event) {
console.log(event.width, event.height);
console.log(event.naturalWidth, event.naturalHeight);
}
readystatechange事件
<img id="myImage" src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/729e29c8adce46ff959150897cf911c1~tplv-k3u1fbpfcp-zoom-1.image" style="width: 50px;" onload="handleOnload(this)">
var img = document.getElementById('myImage');
img1.onreadystatechange = function () {
if(img1.readyState=="complete" ||img1.readyState=="loaded"){}
}
img的complete属性
轮询不断监测img的complete属性,如果为true则表明图片已经加载完毕,停止轮询。该属性所有浏览器都支持。