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

JS and css implement detection of changes in mobile device orientation and judgment of horizontal and vertical screens_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:57:52894browse

Method 1: Use an event to trigger the switch between the horizontal and vertical screens of the phone

Copy code The code is as follows:

window.addEventListener("orientationchange", function() {

// Announce the value of the new direction

alert(window.orientation);

}, false);

Method 2: Monitor resize changes

Copy code The code is as follows:

window.addEventListener("resize", function() {

// Get screen size (inner/outer width, inner/outer height)

}, false);

css determines whether the screen is horizontal or vertical

Copy code The code is as follows:

/* portrait */

@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:

Copy code The code is as follows:

var mql = window.matchMedia("(orientation: portrait)");

// 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

}

});

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn