是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?
当前回答
只需传递input元素获得的“img”文件对象。当我们选择正确的文件时,它将给出图像的自然高度和宽度。
function getNeturalHeightWidth(file) {
let h, w;
let reader = new FileReader();
reader.onload = () => {
let tmpImgNode = document.createElement("img");
tmpImgNode.onload = function() {
h = this.naturalHeight;
w = this.naturalWidth;
};
tmpImgNode.src = reader.result;
};
reader.readAsDataURL(file);
}
return h, w;
}
其他回答
var img = document.getElementById("img_id");
alert( img.height + " ;; " + img .width + " ;; " + img .naturalHeight + " ;; " + img .clientHeight + " ;; " + img.offsetHeight + " ;; " + img.scrollHeight + " ;; " + img.clientWidth + " ;; " + img.offsetWidth + " ;; " + img.scrollWidth )
//But all invalid in Baidu browser 360 browser ...
当页面在JavaScript或jQuery中加载时,你可以像这样应用onload处理程序属性:
$(document).ready(function(){
var width = img.clientWidth;
var height = img.clientHeight;
});
假设,我们想要得到<img id="an-img" src"…" >
// Query after all the elements on the page have loaded.
// Or, use `onload` on a particular element to check if it is loaded.
document.addEventListener('DOMContentLoaded', function () {
var el = document.getElementById("an-img");
console.log({
"naturalWidth": el.naturalWidth, // Only on HTMLImageElement
"naturalHeight": el.naturalHeight, // Only on HTMLImageElement
"offsetWidth": el.offsetWidth,
"offsetHeight": el.offsetHeight
});
})
自然维度
埃尔。naturalWidth和el。naturalHeight会得到图像文件的自然尺寸。
布局尺寸
埃尔。offsetWidth和el。offsetHeight将为我们提供元素在文档上呈现的尺寸。
这是我的方法:
var imgSrc, imgW, imgH;
function myFunction(image) {
var img = new Image();
img.src = image;
img.onload = function() {
return {
src: image,
width: this.width,
height: this.height};
}
return img;
}
var x = myFunction('http://www.google.com/intl/en_ALL/images/logo.gif');
// Waiting for the image loaded. Otherwise, system returned 0 as both width and height.
x.addEventListener('load', function() {
imgSrc = x.src;
imgW = x.width;
imgH = x.height;
});
x.addEventListener('load', function() {
console.log(imgW + 'x' + imgH); // 276x110
});
console.log(imgW); // undefined.
console.log(imgH); // undefined.
console.log(imgSrc); // undefined.
从父div中删除浏览器解释设置是很重要的。所以如果你想要真实的图像宽度和高度,你可以使用
$('.right-sidebar').find('img').each(function(){
$(this).removeAttr("width");
$(this).removeAttr("height");
$(this).imageResize();
});
这是我的一个TYPO3项目示例,我需要图像的真实属性来缩放它与正确的关系。
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 如何在JSON中使用杰克逊更改字段名
- 很好的初学者教程socket.io?
- 点击下载Href图片链接
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置