Home > Article > Web Front-end > JS and css implement detection of changes in mobile device orientation and judgment of horizontal and vertical screens_javascript skills
Method 1: Use an event to trigger the switch between the horizontal and vertical screens of the phone
// Announce the value of the new direction
alert(window.orientation);
}, false);
Method 2: Monitor resize changes
// Get screen size (inner/outer width, inner/outer height)
}, false);
css determines whether the screen is horizontal or vertical
@media screen and (orientation:portrait) {
/* portrait-specific styles */
}
/* landscape */
@media screen and (orientation:landscape) {
/* landscape-specific styles */
}
The native window.matchMedia method allows real-time media querying. We can use the above media query to find out whether we are in an upright or horizontal view:
// If there is a match, we are in vertical view
if(mql.matches) {
//upright direction
alert("1")
} else {
//Horizontal direction
alert("2")
}
//Add a media query change listener
mql.addListener(function(m) {
if(m.matches) {
//Change to upright orientation
document.getElementById("test").innerHTML="Change to upright orientation";
}
else {
document.getElementById("test").innerHTML="Change to horizontal orientation";
//Change to horizontal orientation
}
});