不同设备的实际行为不一致。调整大小和方向更改事件可以按不同的顺序以不同的频率触发。此外,某些值(例如 screen.width 和 window.orientation)并不总是在您预期时更改。避免使用 screen.width -- 在 iOS 中旋转时不会更改。
可靠的方法是同时侦听调整大小和方向更改事件(使用一些轮询作为安全捕获),最终将获得方向的有效值。在我的测试中,Android设备在旋转整整180度时偶尔会无法触发事件,因此我还包含了一个setInterval来轮询方向。
var previousOrientation = window.orientation;
var checkOrientation = function(){
if(window.orientation !== previousOrientation){
previousOrientation = window.orientation;
// orientation changed, do your magic here
}
};
window.addEventListener("resize", checkOrientation, false);
window.addEventListener("orientationchange", checkOrientation, false);
// (optional) Android doesn't always fire orientationChange on 180 degree turns
setInterval(checkOrientation, 2000);
以下是我测试过的四个设备的结果(对不起ASCII表,但这似乎是显示结果的最简单方法)。除了iOS设备之间的一致性之外,设备之间还有很多变化。注意:事件按其触发的顺序列出。
|==============================================================================|
| Device | Events Fired | orientation | innerWidth | screen.width |
|==============================================================================|
| iPad 2 | resize | 0 | 1024 | 768 |
| (to landscape) | orientationchange | 90 | 1024 | 768 |
|----------------+-------------------+-------------+------------+--------------|
| iPad 2 | resize | 90 | 768 | 768 |
| (to portrait) | orientationchange | 0 | 768 | 768 |
|----------------+-------------------+-------------+------------+--------------|
| iPhone 4 | resize | 0 | 480 | 320 |
| (to landscape) | orientationchange | 90 | 480 | 320 |
|----------------+-------------------+-------------+------------+--------------|
| iPhone 4 | resize | 90 | 320 | 320 |
| (to portrait) | orientationchange | 0 | 320 | 320 |
|----------------+-------------------+-------------+------------+--------------|
| Droid phone | orientationchange | 90 | 320 | 320 |
| (to landscape) | resize | 90 | 569 | 569 |
|----------------+-------------------+-------------+------------+--------------|
| Droid phone | orientationchange | 0 | 569 | 569 |
| (to portrait) | resize | 0 | 320 | 320 |
|----------------+-------------------+-------------+------------+--------------|
| Samsung Galaxy | orientationchange | 0 | 400 | 400 |
| Tablet | orientationchange | 90 | 400 | 400 |
| (to landscape) | orientationchange | 90 | 400 | 400 |
| | resize | 90 | 683 | 683 |
| | orientationchange | 90 | 683 | 683 |
|----------------+-------------------+-------------+------------+--------------|
| Samsung Galaxy | orientationchange | 90 | 683 | 683 |
| Tablet | orientationchange | 0 | 683 | 683 |
| (to portrait) | orientationchange | 0 | 683 | 683 |
| | resize | 0 | 400 | 400 |
| | orientationchange | 0 | 400 | 400 |
|----------------+-------------------+-------------+------------+--------------|