jQuery获得响应式图像的高度
我有一组响应页面的图像(即最大宽度设置为100%)。
同
.exh img { max-width:100%; }
在调整窗口大小和加载页面后,如何检索图像的高度? 当我使用以下内容时,我的高度为0。
$(".exh img").each(function() { var $this = $(this); console.log( $this.height() ); });
根据这个答案,我提出了一个类似的问题:
为什么jQuery.css(’width’)在不同的浏览器中返回不同的值?
.width()
或height()
是元素中“呈现在DOM中”的大小 – 并且要返回大于0的值,元素需要完全可用于DOM(也就是图像需要完全可用)加载)
你想要的是:
var myImage= new Image(); myImage.onload=function() { alert(this.height);} myImage.src= "your/image/url";
简而言之 – 您需要在调用height()
之前保证图像已加载
如果您需要在加载页面时以及调整页面大小时执行此操作,请执行以下操作:
$(document).ready( function() { //Fires when DOM is loaded getImageSizes(); $(window).resize(function() { //Fires when window is resized getImageSizes(); }); }); function getImageSizes() { $(".exh img").each(function() { var $this = $(this); console.log( $this.height() ); }); }
有关.resize()的更多信息: http : //api.jquery.com/resize/
有关.ready()的更多信息: http : //api.jquery.com/ready/