Judge horizontal screen and vertical screen (three kinds)

  • 2021-07-21 06:02:47
  • OfStack

When doing mobile pages, it is often necessary to judge whether the horizontal screen or the vertical screen. Below, the known judgment methods of HTML, CSS and JS are recorded for later reading.

1. By referring to the styles of horizontal screen and vertical screen respectively in html:


    <link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css" rel="external nofollow" > // Referring to the vertical screen CSS
    <link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css" rel="external nofollow" > // Referring to the horizontal screen CSS

2. In CSS, it is judged by media query:


@media (orientation: portrait ){
 // Vertical screen CSS 
}
@media ( orientation: landscape ){
 // Horizontal screen CSS 
}

3. js judges whether it is a horizontal screen and a vertical screen:


window.addEventListener("onorientationchange" in window ? orientationchange" : "resize", function() {
  if (window.orientation === 180 || window.orientation === 0) { 
   alert(' Vertical screen status! ');
  } 
  if (window.orientation === 90 || window.orientation === -90 ){ 
   alert(' Horizontal screen status! ');
  } 
 }, false);

The onorientationchange event is triggered whenever the user changes the viewing mode of the device.

orientation has four values: 0, 90,-90, 180

Values of 0 and 180 are vertical screens (180 is the inverted vertical screen);

90 and-90 is horizontal screen (-90 is inverted vertical screen mode);


Related articles: