如何在*因屏幕方向更改而resize后获取元素*的新尺寸?
我正在开发一个移动网络应用程序,在我的页面中,我有一个div
元素,其宽度设置为100%。
我需要设置这个div
的高度,以便高度对于设定的宽高比是正确的。 因此,例如,如果屏幕大小为300像素宽且比例为3:2,我的脚本应该抓住div
的宽度(此时应该是300px)并将高度设置为200px。
在第一次加载时,这非常有效。 但是,如果我将手机的屏幕旋转到横向, div
的宽度会明显改变,所以我需要重置其高度以保持正确的比例。
我的问题是,我找不到在调整元素大小后触发的事件。 jQuery Mobile内置了一个orientationchange
事件,当屏幕从纵向旋转到横向时有助于触发,反之亦然:
$(window).bind('orientationchange', function (e) { // Correctly alerts 'landscape' or 'portrait' when orientation is changed alert(e.orientation); // Set height of div var div = $('#div'); var width = div.width(); // Shows the *old* width, ie the div's width before the rotation alert(width); // Set the height of the div (wrongly, because width is incorrect at this stage) div.css({ height: Math.ceil(width / ratio) }); });
但是这个事件似乎在页面中的任何元素resize以适应新布局之前触发,这意味着(如评论中所述)我只能获得div
的预旋转宽度,这不是我需要的。
事情已经调整好自己,有谁知道我怎么能得到div
的新宽度?
您可以尝试以下几种方法:
(1)在orientationchange
事件处理程序中设置超时,以便DOM可以自行更新,浏览器可以在轮询新维度之前绘制所有更改:
$(window).bind('orientationchange', function (e) { setTimeout(function () { // Get height of div var div = $('#div'), width = div.width(); // Set the height of the div div.css({ height: Math.ceil(width / ratio) }); }, 500); });
它不会产生太大的差异,但请注意Math.ceil
需要比Math.floor
更长的时间来完成(相对),因为后者只需要丢弃小数点后的所有内容。 我通常只是在浏览器中传递未触摸的浮点数,然后将其舍入到想要的位置。
(2)使用window.resize
事件来查看更新是否足够快:
$(window).bind('resize', function (e) { // Get height of div var div = $('#div'), width = div.width(); // Set the height of the div div.css({ height: Math.ceil(width / ratio) }); });
在移动设备上,当方向发生变化时会触发,因为浏览器视口的大小也会发生变化。
(3)如果要更新此
元素的大小,因为它包含图像,只需将一些CSS应用于图像,使其始终为全宽和正确的宽高比:
.my-image-class { width : 100%; height : auto; }