是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?
当前回答
其他所有人都忘记了的事情是,你不能在加载前检查图像大小。当作者检查所有发布的方法时,它可能只在本地主机上工作。
由于这里可以使用jQuery,请记住'ready'事件是在图像加载之前触发的。$('#xxx').width()和.height()应该在onload事件或以后触发。
其他回答
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]);
}
这适用于多个图像预览和上传。如果你必须为每个图像逐一选择,然后复制粘贴到所有预览图像功能和验证!!
Try
函数大小(){ console.log(“宽度:${照片。宽度},高度:$ {pic.height}’); } <img id="pic" src="https://picsum.photos/300/150"> <按钮onclick = "尺寸()“>显示> < /按钮大小
const file = event.target.files[0];
const img = new Image();
img.onload = function () {
width = img.width;
height = img.height;
};
img.src = URL.createObjectURL(file);
alert(width + "x" + height);
尼基·德·梅耶要了一张背景照片;我只是从CSS内容中获取它,并替换“url()””:
var div = $('#my-bg-div');
var url = div.css('background-image').replace(/^url\(\'?(.*)\'?\)$/, '$1');
var img = new Image();
img.src = url;
console.log('img:', img.width + 'x' + img.height); // Zero, image not yet loaded
console.log('div:', div.width() + 'x' + div.height());
img.onload = function() {
console.log('img:', img.width + 'x' + img.height, (img.width/div.width()));
}
我认为这可能对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输入的清除?
- 字符串中的单词大写