javascript - 旋转时重置 CSS

标签 javascript css

我正在使用一些 CSS 来设置我页面上图像元素的大小。问题是,如果用户旋转他们的手机,它会保持固定在原始尺寸上。有没有办法检测旋转,并重新计算元素应该在页面上的大小?

这是我到目前为止发现的...

window.addEventListener("orientationchange", function() {}, false);

最佳答案

当然,您可以使用 CSS media queries对于这类事情:

/* Portrait */
@media screen and (orientation:portrait) {
    /* Portrait styles */
}
/* Landscape */
@media screen and (orientation:landscape) {
    /* Landscape styles */
}

A media query consists of a media type and at least one expression that limits the style sheets' scope by using media features, such as width, height, and color. Media queries, added in CSS3, let the presentation of content be tailored to a specific range of output devices without having to change the content itself.

如果您想扩展和定位桌面设备与移动设备等,您可以将媒体查询扩展到相当具体。

或者 - 使用 JS 你可以简单地做:

var orientation = null;
window.onresize = function (event) {
    orientation = parseInt(window.innerHeight / window.innerWidth) !== 0 ? 'portrait' : 'landscape';
    /* logic for if orientation == portrait etc goes here */
};

关于javascript - 旋转时重置 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23223620/

相关文章:

html - 带表格单元格的 Div 只能使用 1 次

css - 输入验证消息不消失

javascript - 将图像缩放到窗口的宽度

c# - 我需要帮助翻译这部分 ECMAScript 语法吗?

javascript - 带信息窗口的多个标记

javascript - 当一行中的元素数量可变时,如何使用 jQuery 为每一行着色?

javascript - 页脚使用https://www.tesla.com/charging使用什么方法?

javascript - 奇怪的 Javascript 日期差异

javascript - 具有多个图的 D3 转换

javascript - 使用观察检测 Javascript 数组中的更改,但不与另一个数组进行比较