几个方法供你尝试:
(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)如果您要更新此大小<div>
元素因为它包含图像,只需对图像应用一些 CSS 即可使其始终为全角和正确的宽高比:
.my-image-class {
width : 100%;
height : auto;
}