CSS section
First, create a new class for judgment, and then use Media Queries to assign different values to the z-index attribute of this class. This class is only used as JavaScript read, so it needs to be moved out of the screen window so that the viewer is invisible to avoid unexpected situations.
As a demonstration, the following code sets four device statuses: desktop normal version, small screen desktop version, tablet version and mobile version.
/* 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 already in place, so you need to use JavaScript to generate a temporary DOM object, then set the corresponding class for it, and then read the z-index value of this object. The native writing 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);}getDeviceState() The function returns the value of z-index. In order to enhance readability, you can use switch Functions to standardize 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 under the tablet}If you are using jQuery here, just use the following code:
$(function(){ $('body').append('<div></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 first, then obtain, and finally delete this node. The specific device will be output in your console. Click here to view the demo. You can try to drag the middle border and click Run.