JavaScript uses CSS Media Queries to determine how devices are browsed. cssqueries
CSS Section
First, create a new class for judgment, and then assign different values to the z-index attribute of the class through Media Queries. This class is only used for reading JavaScript, so you need to remove it from the screen window so that the viewer is invisible to avoid unexpected situations.
For demonstration, the following code sets four device statuses: basic desktop edition, small-screen desktop edition, tablet edition, and mobile edition.
/* default state */.state-indicator { position: absolute; top: -999em; left: -999em; z-index: 1;}/* small desktop */@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; }}
JavaScript judgment
CSS is in place, so you need to use JavaScript to generate a temporary DOM object, set the corresponding class for it, and then read the z-index value of this object. The native method is as follows:
// Create the state-indicator elementvar indicator = document. createElement ('div '); indicator. className = 'state-indicator'; document. body. appendChild (indicator); // Create a method which returns device statefunction getDeviceState () {return parseInt (window. getComputedStyle (indicator ). getPropertyValue ('z-Index'), 10);} The value returned by the getDeviceState () function is the value of z-index. To improve readability, you can use the switch function to standardize the output: function getDeviceState () {switch (parseInt (window. getComputedStyle (indicator ). getPropertyValue ('z-Index'), 10) {case 2: return 'small-desktop '; break; case 3: return 'tablet'; break; case 4: return 'phone'; break; default: return 'desktop '; break ;}}
In this way, you can use the following code to determine the device status and then execute the corresponding JavaScript code:
If (getDeviceState () = 'tablet') {// JavaScript code executed on the tablet}
If you are using jQuery, you can directly use the following code:
$(function(){ $('body').append('<div class="state-indicator"></div>'); function getDeviceState() { switch(parseInt($('.state-indicator').css('z-index'),10)) { case 2: return 'small-desktop'; break; case 3: return 'tablet'; break; case 4: return 'phone'; break; default: return 'desktop'; break; } } console.log(getDeviceState()); $('.state-indicator').remove();});
Create a node, obtain the node, and delete the node. The device will output the node in your console. Click here to view the Demo. You can drag the border in the middle and click Run.