是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?
当前回答
如果你正在使用jQuery并且你正在请求图像大小,你必须等待它们加载,否则你只会得到零。
$(document).ready(function() {
$("img").load(function() {
alert($(this).height());
alert($(this).width());
});
});
其他回答
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 ...
Use
function outmeInside() {
var output = document.getElementById('preview_product_image');
if (this.height < 600 || this.width < 600) {
output.src = "http://localhost/danieladenew/uploads/no-photo.jpg";
alert("The image you have selected is low resolution image. Your image width=" + this.width + ", height=" + this.height + ". Please select image greater or equal to 600x600. Thanks!");
}
else {
output.src = URL.createObjectURL(event.target.files[0]);
}
return;
}
img.src = URL.createObjectURL(event.target.files[0]);
}
这适用于多个图像预览和上传。如果你必须为每个图像逐一选择,然后复制粘贴到所有预览图像功能和验证!!
在获取元素的属性之前,文档页面应该是onload的:
window.onload = function(){
console.log(img.offsetWidth,img.offsetHeight);
}
假设,我们想要得到<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将为我们提供元素在文档上呈现的尺寸。
我想我改进了源代码,以便能够在尝试找出其属性之前让图像加载。否则,它将显示'0 * 0',因为下一个语句将在文件加载到浏览器之前被调用。它需要jQuery…
function getImgSize(imgSrc) {
var newImg = new Image();
newImg.src = imgSrc;
var height = newImg.height;
var width = newImg.width;
p = $(newImg).ready(function() {
return {width: newImg.width, height: newImg.height};
});
alert (p[0]['width'] + " " + p[0]['height']);
}
推荐文章
- 在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输入的清除?
- 字符串中的单词大写