是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?
当前回答
这是我的方法:
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项目示例,我需要图像的真实属性来缩放它与正确的关系。
在使用真实图像大小之前,您应该加载源图像。如果使用jQuery框架,可以以简单的方式获得真实图像大小。
$("ImageID").load(function(){
console.log($(this).width() + "x" + $(this).height())
})
这个答案正是我所寻找的(在jQuery):
var imageNaturalWidth = $('image-selector').prop('naturalWidth');
var imageNaturalHeight = $('image-selector').prop('naturalHeight');
在获取元素的属性之前,文档页面应该是onload的:
window.onload = function(){
console.log(img.offsetWidth,img.offsetHeight);
}
我认为这可能对2019年使用JavaScript和/或TypeScript的人有所帮助。
我发现以下内容是不正确的,就像一些人认为的那样:
let img = new Image();
img.onload = function() {
console.log(this.width, this.height) // Error: undefined is not an object
};
img.src = "http://example.com/myimage.jpg";
这是正确的:
let img = new Image();
img.onload = function() {
console.log(img.width, img.height)
};
img.src = "http://example.com/myimage.jpg";
结论:
在onload函数中使用img,而不是this。
推荐文章
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- 用jQuery检查Internet连接是否存在?
- 如何使用滑动(或显示)函数在一个表行?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量
- 如何用JavaScript截屏一个div ?
- 如何为其他域设置cookie
- 如何减去日期/时间在JavaScript?
- 如何检测“搜索”HTML5输入的清除?
- 字符串中的单词大写