Is it possible to detect on my page, for example using Javascript, when user visit it using mobile device in portrait mode, and stop orientation changing when user rotate its phone to landscape? There is game on my page, optimized for portrait display only and I don't want it in landscape.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
seems weird that no one proposed the CSS media query solution:
and the option to use a specific style sheet:
MDN: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries#orientation
Simple Javascript code to make mobile browser display either in portrait or landscape..
(Even though you have to enter html code twice in the two DIVs (one for each mode), arguably this will load faster than using javascript to change the stylesheet...
Tested and works on Android HTC Sense and Apple iPad.
With the new CSS3 features, you could rotate the page the opposite orientation that they rotated. Sorry, no IE7- support. :(.
You can detect the orientation change, but I don't think you can prevent it.
In JavaScript-enabled browsers it should be easy to determine if the screen is in landscape or portrait mode and compensate using CSS. It may be helpful to give users the option to disable this or at least warn them that device rotation will not work properly.
Edit
The easiest way to detect the orientation of the browser is to check the width of the browser versus the height of the browser. This also has the advantage that you'll know if the game is being played on a device that is naturally oriented in landscape mode (as some mobile devices like the PSP are). This makes more sense than trying to disable device rotation.
Edit 2
Daz has shown how you can detect device orientation, but detecting orientation is only half of the solution. If want to reverse the automatic orientation change, you'll need to rotate everything either 90° or 270°/-90°, e.g.
Note: if you want to rotate in IE by an arbitrary angle (for other purposes), you'll need to use matrix transform, e.g.
—or use CSS Sandpaper. Also, this applies the rotation style to the window object, which I've never actually tested and don't know if works or not. You may need to apply the style to a document element instead.
Anyway, I would still recommend simply displaying a message that asks the user to play the game in portrait mode.
You could use the screenSize.width and screenSize.height properties and detect when the width > height and then handle that situation, either by letting the user know or by adjusting your screen accordingly.
But the best solution is what @Doozer1979 says... Why would you override what the user prefers?