是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?
当前回答
最近我有同样的问题,在一个错误的伸缩滑块。由于加载延迟,第一张图像的高度被设置得较小。我尝试了以下方法来解决这个问题,它是有效的。
// Create an image with a reference id. Id shall
// be used for removing it from the DOM later.
var tempImg = $('<img id="testImage" />');
// If you want to get the height with respect to any specific width you set.
// I used window width here.
tempImg.css('width', window.innerWidth);
tempImg[0].onload = function () {
$(this).css('height', 'auto').css('display', 'none');
var imgHeight = $(this).height();
// Remove it if you don't want this image anymore.
$('#testImage').remove();
}
// Append to body
$('body').append(tempImg);
// Set an image URL. I am using an image which I got from Google.
tempImg[0].src ='http://aspo.org/wp-content/uploads/strips.jpg';
这将为您提供相对于您设置的宽度的高度,而不是原始宽度或零。
其他回答
用jQuery库-
使用.width()和.height()。
更多jQuery宽度和jQuery高度。
示例代码:
$(文档)时函数(){ $("按钮”).click(函数() { alert(”图像的宽度 : " + $("# img_exmpl”).width ()); alert("形象的高度 : " + $("# img_exmpl”).height ()); }); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js " > < /脚本> <img id="img_exmpl" src="http://images.all-free-download.com/images/graphicthumb/beauty_of_nature_9_210287.jpg"> <button> img显示尺寸</button>
Try
函数大小(){ console.log(“宽度:${照片。宽度},高度:$ {pic.height}’); } <img id="pic" src="https://picsum.photos/300/150"> <按钮onclick = "尺寸()“>显示> < /按钮大小
其他所有人都忘记了的事情是,你不能在加载前检查图像大小。当作者检查所有发布的方法时,它可能只在本地主机上工作。
由于这里可以使用jQuery,请记住'ready'事件是在图像加载之前触发的。$('#xxx').width()和.height()应该在onload事件或以后触发。
假设,我们想要得到<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将为我们提供元素在文档上呈现的尺寸。
clientWidth和clienttheight是DOM属性,显示DOM元素内部维度的当前浏览器大小(不包括边距和边框)。在IMG元素的情况下,这将得到可见图像的实际尺寸。
var img = document.getElementById('imageid');
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
推荐文章
- 在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输入的清除?
- 字符串中的单词大写