JS and CSS to detect changes in the direction of mobile devices and determine the screen _javascript skills

Source: Internet
Author: User

Method one: To trigger the phone between the horizontal screen and the vertical screen switch between the event

Copy Code code as follows:

Window.addeventlistener ("Orientationchange", function () {

The value of announcing the new direction

alert (window.orientation);

}, False);

Method Two: Monitor the resizing changes

Copy Code code as follows:

Window.addeventlistener ("Resize", function () {

Get screen size (internal/external width, internal/external height)

}, False);

CSS to judge the screen

Copy Code code 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:

Copy Code code 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

}

});

Related Article

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.