CSS section
Start by creating a class to make judgments, and then use Media Queries to assign different values to the Z-index property of the class. This class is used only as a JavaScript read, so it needs to be moved out of the screen window so that the visitors are not visible to avoid unexpected situations.
As a demonstration, the following code sets four device statuses: desktop normal, small screen desktop, tablet and mobile.
/* 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 a ll and (max-width:1024px) { . state-indicator { z-index:3; }}/* mobile phone */@media all and (max-width:7 68px) { . state-indicator { z-index:4; }}
JavaScript judgment
CSS is already in place, then you need to use JavaScript to generate a temporary DOM object, then set the corresponding class for it, and then read the object's Z-index value. The native wording is as follows:
Create the state-indicator Elementvar indicator = document.createelement (' div '); indicator.classname = ' State-indicator ';d ocument.body.appendChild (indicator); Create a method which returns device Statefunction Getdevicestate () { return parseint (window.getComputedStyle ( Indicator). GetPropertyValue (' Z-index '), 10);} The Getdevicestate () function returns the value of Z-index, in order to enhance readability, you can use the switch function to standardize the output: function Getdevicestate () { switch (parseint ( window.getComputedStyle (indicator). GetPropertyValue (' Z-index ')) {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 code to determine the state of the device, and then execute the appropriate JavaScript code :
if (getdevicestate () = = ' tablet ') { //* JavaScript code executed under tablet}
If you are using jQueryhere, use the following code directly:
$ (function () { $ (' body '). Append (' <div class= "State-indicator" ></div> "); function Getdevicestate () { switch (parseint ($ ('. State-indicator '). CSS (' Z-index '), +) {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 ();});
JavaScript determines how to browse devices based on the media queries of the CSS