Clever use of CSS media query (media Queries) and JavaScript to determine the browser device type of a good way

Source: Internet
Author: User

There are countless reasons to ask us at any time to know what device users are using to browse our website-widescreen, normal screen, tablet, mobile phone? Knowing these features, the CSS and JavaScript of our web app can do the same thing synchronously. In the process of designing for Mozilla Developer Networks, I found that using CSS media queries is very effective, but sometimes JavaScript doesn't know the state of the user's browsing device in time. Does the user browsing the website use a desktop computer, a tablet, or a mobile phone? This is easy for CSS, but CSS is not able to tell JavaScript about it. I invented a method based on CSS media queries and z-index attributes that tells JavaScript users what screen they are currently using, so I can adjust the action of JavaScript to respond to this screen size.

CSS Code

The first and foremost is the CSS Media query code. Here is just an example, we created three media query rules (but not the default "all"), it can control four kinds of screen situation: desktop (this is the default state, no media query rules), "small screen", tablet, mobile phone. For each screen, we give it a different z-index value, which we can detect with JavaScript. We put this element out of the screen so it doesn't show up; remember, it's about storing z-index values, and we're going to use JavaScript to get that value.

/* Default screen */. state-indicator{Position: Absolute;Top: -999em;Left: -999em;Z-index: 1;}/* Small screen */@media All and (max-width: 1200px){. state-indicator{Z-index: 2;}}/* flat */ @media all and (max-width {.state-indicator { z-index}}/* mobile */ @media all and (Max-width{.state-indicator {z-index< Span class= "token punctuation" >: 4}}        /span>              

Each z-index one tells us the JavaScript current user is using what size of the screen. It's not like we know what device the user is using, because you can pull the width of the browser very narrow, but we need to be the visible width, so we can adjust the layout of the app.

JavaScript code

Maybe you think you can know the size of the screen at the DomContentLoaded time, but we need to know the size of the screen in real time (because the user adjusts the size of the browser window), we need a way to get the properties of the current window:

To create a status indicator elementvar indicator= document.CreateElement(' Div '); indicator. className=' State-indicator ';d ocument. body.AppendChild(indicator);//get device class methods function  Getdevicestate ( {return parseint ( Window. Getcomputedstyle (Indicatorgetpropertyvalue () 10;}      

Using this method, you will be able to detect the layout of the page/js the ones that need to be shown and those that need to be hidden.

If(getdevicestate(3{ //Display JS trim ....) }

Some people may think that these numbers are too easy to make mistakes, making the code difficult to maintain. In fact, we can use an object to deal with this kind of thing:

functionGetdevicestate(){var index=parseint(Window.getComputedStyle(indicator).GetPropertyValue(' Z-index '),10)var states = {2 ' small-desktop ' 3:  ' tablet ' 4 ' phone ' }; return states[index ] | |  ' desktop ' ;}    

In this way, you will write a more readable logical judgment:

If(getdevicestate(' tablet ' //Do whatever}     

Perhaps the property of a pseudo-element using CSS content is a better approach:

. state-indicator{Position: Absolute;Top: -999em;Left: -999em;}. state-indicator:before{Content:' Desktop ';}/* Small screen Desktop */@media All and (max-width: 1200px){. state-indicator:before{Content:' Small-desktop ';}}/* Tablet */@media All and (max-width{.state-indicator:before {content:  ' tablet ' ; }}/* Mobile */ @media all and (Max-width{ Span class= "token selector" >.state-indicator:before { content:  ' mobile ' }}        /span>              

Use the following JavaScript method to get the key content:

= Window.  getComputedStyle(    document.  Queryselector('. State-indicator ')': Before ').  GetPropertyValue(' content ')            

How to organize the code is all about you. If you have a global object, such as window.config or, window.app you can put these methods inside. I tend to modularize these features, you can make it into a jquery plugin or JavaScript toolkit. No matter how you do it, they are a great way to rely on easy-to-use, user-friendly device detection.

Better

We know that the screen size will change-the user manually adjusts the browser to large or mobile phone users to adjust the direction of the phone, so when these events occur, we need to let the system tell us. The following simple code estimate is what you need:

var lastdevicestate=Getdevicestate(); window.AddEventListener(' Resize ',Debounce(function(){var state=Getdevicestate();If(state!= Lastdevicestate){Keep the current state lastdevicestate= State;Declares a state change through a custom DOM event or JS message Publish/Subscribe mode,I like the latter, all assuming that a tool library like this is usedPublish('/device-state/change ',[State]);}},20) ;//usage subscribe (  '/device-state/change '  Function{if (state == 3) {//or "tablet", if you used the object }})  ; 

Note that I used the debounce method here to perform resize the action when the event occurred--which is very important for performance. Whether you use a custom DOM event or a publish/subscribe model, you are free to choose because it is simple.

I think this method is very good. One might point out that use matchMedia can have the same effect, but the problem is that you need to use media queries both in CSS and in JavaScript, and some media query statements can be complex or even a nightmare, rather than simple to use z-index . Some people will say that can be used window.innerWidth to judge, but so that the attributes of JS and the media query in the CSS need to convert each other, the same will become your demon. The advantage of my approach is that you can use it to determine other types of media query properties, such as checking whether the phone is landscape ( landscape ) or Vertical ( portrait ).

Anyway, you can try it and tell me how you feel!

Clever use of CSS media query (media Queries) and JavaScript to determine the browser device type of a good way

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.