Unless your application limits the use of mobile devices only in the upright or horizontal state, you will normally need to adjust some settings. Even if you design a sleek layout, you may need to change some programming code. There are usually several small strategies for detecting changes in the direction of a mobile device.
Orientationchange Events
You wait for a mobile API, a simple window Orientationchange event:
- Change in the direction of listening
- Window.addeventlistener ("Orientationchange", function () {
- The value of announcing the new direction
- alert (window.orientation);
- }, False);
The window.orientation attribute changes when the change occurs. A value of 0 indicates an upright, 90 means the device rotates horizontally to the left, and 90 indicates that the device is rotated horizontally to the right.
resizing events
Some devices do not support orientationchange events, but can trigger resize events:
- Monitor resizing changes
- Window.addeventlistener ("Resize", function () {
- Get screen size (internal/external width, internal/external height)
- }, False);
Compared with the Orientationchange incident is less obvious, but also very useful.
Screen size
There are some properties that can be recovered from the window object to get the screen size and I think the virtual screen size:
- Outer width, outer height: pixels that are really fixed (rather than 320x356iphone vertical pixels)
- Internal width, Internal height: virtual motionless pixels (instead of 320x356iphone upright pixels)
Of course, this data does not tell you the direction of the change, you need to pass the mathematical calculation, you know whether the current window state is wider or higher.
Media inquiries
You can also use CSS Media query to determine the direction:
- * Portrait * *
- @media screen and (orientation:portrait) {
- /* portrait-specific Styles * *
- }
- * Landscape * *
- @media screen and (Orientation:landscape) {
- /* landscape-specific Styles * *
- }
It's smarter to write a loop of "Watcher" in JavaScript to check the background color of a block and trigger your own change in direction.
Matching Media
The local Window.matchmedia method allows real-time media queries. We can use the above media query to find that we are in an upright or horizontal perspective:
- Find a match
- var mql = Window.matchmedia ("(orientation:portrait)");
- If there is a match, we are in the vertical view
- Upright direction
- Horizontal direction
- }
- Add a media query change supervisor
- Mql.addlistener (function (m) {
- if (m.matches) {
- Change to the upright direction
- }
- else {
- Change to a horizontal direction
- }
- });
These are some suggestions, I also hope to collect more people's methods!