This article mainly introduces JS and CSS to detect the changes in the direction of mobile devices and judge the screen, this article gives the implementation code, the need for friends can refer to the
Method one: To trigger the phone between the horizontal screen and the vertical screen switch between the event
The code is as follows:
Window.addeventlistener ("Orientationchange", function () {
The value of announcing the new direction
alert (window.orientation);
}, False);
Method Two: Monitor the resizing changes
The code is as follows:
Window.addeventlistener ("Resize", function () {
Get screen size (internal/external width, internal/external height)
}, False);
CSS to judge the screen
The complex 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 above media query to find that we are in an upright or horizontal perspective:
The code is as follows:
var mql = Window.matchmedia ("(orientation:portrait)");
If there is a match, we are in the vertical view
if (mql.matches) {
Upright direction
Alert ("1")
} else {
Horizontal direction
Alert ("2")
}
Add a media query change supervisor
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 a horizontal direction
}
});