Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of determining the type of browser device using CSS media query and JavaScript

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Today, I'll talk to you about how to use CSS media query and JavaScript to judge the type of browser device. maybe many people don't know much about it. In order to make you understand better, the editor summarized the following. I hope you can get something from this article.

There are countless reasons why we should know at all times what devices users are using to browse our website-wide screen, regular screen, tablet, mobile phone. Knowing these characteristics, the CSS and JavaScript of our web application can do the corresponding operation synchronously. In the process of redesigning Mozilla Developer Networks, I found that using CSS Media query (media queries) was very effective, but sometimes JavaScript could not know the status of the user browsing the device in time. Do users who browse the website use a desktop, a tablet, or a mobile phone? This is easy for CSS, but CSS cannot tell JavaScript this information. I invented a method based on CSS media queries and z-index properties to tell JavaScript users what screen they are currently using so that I can adjust the action of JavaScript to respond to this screen size.

CSS code

First of all, the most important thing is the CSS media query code. Here are just examples. We have created three media query rules (but not the default "all"), which can control four screen situations: desktop (which is the default state and does not require media query rules), "small screen", tablet, and mobile phone. For each screen, we give it a different z-index value, which we can detect with JavaScript. Let's position this element off the screen so that it doesn't show up; remember, its purpose is to store the z-index value, which we want to get with javaScript.

The code is as follows:

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

}

}

/ * tablet * /

@ media all and (max-width: 1024px) {

. state-indicator {

Z-index: 3

}

}

/ * Mobile phone * /

@ media all and (max-width: 768px) {

. state-indicator {

Z-index: 4

}

}

Each z-index tells us what kind of screen the current user of JavaScript is using. We don't want to know exactly what device the user is using, because you can pull the browser width very narrow, but we need the visual width so that we can adjust the layout of the application.

JavaScript code

You may think you can know the screen size during DomContentLoaded, but we need to know the screen size in real time (because the user will resize the browser window), and we need a way to get the properties of the current window:

The code is as follows:

/ / create a status indicator element

Var indicator = document.createElement ('div')

Indicator.className = 'state-indicator'

Document.body.appendChild (indicator)

/ / method of obtaining device category

Function getDeviceState () {

Return parseInt (window.getComputedStyle (indicator) .getPropertyValue ('zMeiindex'), 10)

}

Using this method, you can detect which page layout / js decorations need to be displayed and which need to be hidden.

The code is as follows:

If (getDeviceState () < 3) {/ / if it is a desktop computer with a small screen

/ / display js ornaments.

}

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

The code is as follows:

Function getDeviceState () {

Var index = parseInt (window.getComputedStyle (indicator) .getPropertyValue ('zmuri index'), 10)

Var states = {

2: 'small-desktop'

3: 'tablet'

4: 'phone'

}

Return states [index] | | 'desktop'

}

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

The code is as follows:

If (getDeviceState ()) = = 'tablet') {

/ / Do whatever

}

Perhaps it is better to use the content attribute of the pseudo element of CSS:

The code is as follows:

. 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: 1024px) {

.state-indicator:before {content: 'tablet';}

}

/ * Mobile phone * /

@ media all and (max-width: 768px) {

.state-indicator:before {content: 'mobile';}

}

Use the following JavaScript method to get the key content:

The code is as follows:

Var state = window.getComputedStyle (

Document.querySelector ('.state-indicator'),': before'

). GetPropertyValue ('content')

How you organize the code is up to you. If you have a global object, such as window.config or window.app, you can put these methods in it. I tend to modularize these functions, and you can turn them into jQuery plug-ins or JavaScript toolkits. No matter how you implement them, they are a reliable, easy-to-use way to detect user devices.

You will enjoy a grander sight

We know that the screen size will change-the user manually adjusts the browser or the mobile user reorients the phone, so when these events happen, we need to let the system tell us. The following simple code is probably what you need:

The code is as follows:

Var lastDeviceState = getDeviceState ()

Window.addEventListener ('resize', debounce (function ()) {

Var state = getDeviceState ()

If (state! = lastDeviceState) {

/ / maintain the current state

LastDeviceState = state

/ / announce status changes through custom DOM events or JS message publish / subscribe mode

/ / I like the latter, so let's assume that such a tool library is used.

Publish ('/ device-state/change', [state])

}

}, 20))

/ / usage

Subscribe ('/ device-state/change', function (state) {

If (state = = 3) {

/ / or "tablet", if you used the object

}

});

Note that here I use the debounce method to perform the action when the resize event occurs-- which is very important for performance. You are free to choose whether to use custom DOM events or publish / subscribe mode, because it is very simple.

I think this method is very good. Some people may point out that using matchMedia can have the same effect, but the problem is that you need to use media queries in both CSS and JavaScript, and some media queries can be complex and even a nightmare, so use a simple z-index. Some people will say that you can use window.innerWidth to judge, but in this way, the attributes acquired in JS and the media queries in CSS need to be converted to each other, and will also become your demons. The advantage of my method is that you can use it to determine other types of media query properties, such as checking whether the phone is landscape or portrait.

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

After reading the above, do you have any further understanding of the method of using CSS media query and JavaScript to determine the type of browser device? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report