如何在*因屏幕方向改变而调整大小后获得元素*的新尺寸?

Mar*_*ell 3 javascript mobile jquery jquery-mobile

我正在开发一个移动网络应用程序,在我的页面中,我有一个div宽度设置为100%的元素.

我需要设置它的高度,div以便高度对于设定的纵横比是正确的.因此,例如,如果屏幕大小为300像素宽并且比例为3:2,我的脚本应该抓住宽度div(此时应该是300px)并将高度设置为200px.

在第一次加载时,这非常有效.但是,如果我将手机的屏幕旋转到横向,则宽度会div明显改变,所以我需要重置其高度以保持正确的比例.

我的问题是我无法找到一个在元素调整大小触发的事件.orientationchangejQuery Mobile内置了一个事件,当屏幕从纵向旋转到横向时有助于触发,反之亦然:

$(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, i.e 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) });

});
Run Code Online (Sandbox Code Playgroud)

但是这个事件似乎在页面中的任何元素调整大小以适应新布局之前触发,这意味着(如评论中所述)我只能得到预旋转宽度div,这不是我需要的.

事情调整好之后div,有谁知道我怎么能得到新的宽度?

Jas*_*per 9

一些方法供您尝试:

(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);
});
Run Code Online (Sandbox Code Playgroud)

它不会产生太大的差异,但注意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) });
});
Run Code Online (Sandbox Code Playgroud)

在移动设备上,当方向发生变化时会触发,因为浏览器视口的大小也会发生变化.

(3)如果要更新此<div>元素的大小,因为它包含图像,只需将一些CSS应用于图像,使其始终为全宽和正确的宽高比:

.my-image-class {
    width  : 100%;
    height : auto;
}
Run Code Online (Sandbox Code Playgroud)