JS and css are used to detect changes in the direction of mobile devices and determine whether the screen is horizontal or vertical.
Method 1: Use the trigger to switch between the portrait and landscape screens of the mobile phone
Copy codeThe Code is as follows:
Window. addEventListener ("orientationchange", function (){
// Announce the value of the new direction
Alert (window. orientation );
}, False );
Method 2: Change the listener size
Copy codeThe Code is as follows:
Window. addEventListener ("resize", function (){
// Obtain the screen size (internal/external width, internal/external height)
}, False );
Css screen Identification
Copy codeThe Code is as follows:
/* Portrait */
@ Media screen and (orientation: portrait ){
/* Portrait-specific styles */
}
/* Landscape */
@ Media screen and (orientation: landscape ){
/* Landscape-specific styles */
}
The local window. matchMedia method allows real-time media queries. We can use the preceding media queries to find that we are in an upright or horizontal view:
Copy codeThe Code is as follows:
Var mql = window. matchMedia ("(orientation: portrait )");
// If there is a match, we are in the vertical angle of view
If (mql. matches ){
// Orientation
Alert ("1 ")
} Else {
// Horizontal direction
Alert ("2 ")
}
// Add a media query to change the listener
Mql. addListener (function (m ){
If (m. matches ){
// Change to the upright direction
Document. getElementById ("test"). innerHTML = "change to upright direction ";
}
Else {
Document. getElementById ("test"). innerHTML = "change to horizontal direction ";
// Change to the horizontal direction
}
});