CSS section
First, create a new class that you can use 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 you need to move it out of the screen window so that the viewer is not visible so that it doesn't cause any surprises.
As a demo, the following code sets four device states: Desktop Normal, small screen desktop, Tablet PC 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 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, 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 original wording is as follows:
Create the State-indicator element
var indicator = document.createelement (' div ');
Indicator.classname = ' state-indicator ';
Document.body.appendChild (indicator);
Create a method which returns device state
function getdevicestate () {return
parseint ( window.getComputedStyle (indicator). GetPropertyValue (' Z-index ');
The Getdevicestate () function returns the value of the Z-index, in order to enhance readability, you can use the switch function to specification output:
function Getdevicestate () {
switch ( parseint (window.getComputedStyle (indicator). GetPropertyValue (' Z-index ') (a)) {case
2: Return
' Small-desktop ';
break;
Case 3: Return
' tablet ';
break;
Case 4: Return
' phone ';
break;
Default: Return
' Desktop ';
break;
}
}
This allows you to use the code to determine the status of the device and then execute the appropriate JavaScript code:
if (getdevicestate () = = ' tablet ') {
//JavaScript code executed under the Tablet PC
}
Here if you are using JQuery, 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 ();
});
First create, then get, and finally delete this node, the specific device will output in your console, click here to view the Demo, you can try to drag the middle of the border, and then click Run.