是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?
当前回答
尼基·德·梅耶要了一张背景照片;我只是从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()));
}
其他回答
简单地说,您可以像这样进行测试。
<script>
(function($) {
$(document).ready(function() {
console.log("ready....");
var i = 0;
var img;
for(i=1; i<13; i++) {
img = new Image();
img.src = 'img/' + i + '.jpg';
console.log("name : " + img.src);
img.onload = function() {
if(this.height > this.width) {
console.log(this.src + " : portrait");
}
else if(this.width > this.height) {
console.log(this.src + " : landscape");
}
else {
console.log(this.src + " : square");
}
}
}
});
}(jQuery));
</script>
这个答案正是我所寻找的(在jQuery):
var imageNaturalWidth = $('image-selector').prop('naturalWidth');
var imageNaturalHeight = $('image-selector').prop('naturalHeight');
您可以通过编程方式获取图像并使用JavaScript检查尺寸…
const img = new Image(); img。Onload = function() { 警报(这。Width + 'x' + this.height); } img。src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
如果图像不是标记的一部分,这可能很有用。
在使用真实图像大小之前,您应该加载源图像。如果使用jQuery框架,可以以简单的方式获得真实图像大小。
$("ImageID").load(function(){
console.log($(this).width() + "x" + $(this).height())
})
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 foreach循环
- 实例化模块失败[$injector:unpr]未知提供者:$routeProvider
- 如何在JavaScript交换两个变量
- 如何从一个变量设置一个JS对象属性名
- 在JavaScript中转换为字符串
- 在jQuery中检测输入[type=text]的值变化
- +0和-0是一样的吗?
- 转换php数组到Javascript
- 如何跳转到浏览器页面的顶部
- CSS: 100%的宽度或高度,同时保持纵横比?
- 确定$。Ajax错误是一个超时
- 在电子邮件消息中是否支持JavaScript ?
- 如何在JavaScript中指定Math.log()的基?
- 多重左赋值JavaScript
- 使用jQuery创建、读取和删除cookie