Javascript and css are used to detect changes in the direction of mobile devices and determine whether the screen is horizontal or vertical. _ javascript skills

Source: Internet
Author: User
This article mainly introduces JS and css implementation to detect changes in the direction of mobile devices and determine whether the screen is horizontal or vertical. This article provides implementation code respectively. For more information, see Method 1: Use the trigger to switch between the portrait and landscape screens of the mobile phone

The 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

The Code is as follows:


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

// Obtain the screen size (internal/external width, internal/external height)

}, False );

Css screen Identification

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

The 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

}

});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.