Home > Article > Web Front-end > How to determine the screen size to automatically execute js? _html/css_WEB-ITnose
Want to automatically hide a div when the screen width is less than 800px
<div id="div"></div>
var browserWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;if(browserWidth<800){ document.getElementById("div").style.display="none";}
Borrowing the code above, my suggestion is actually this. Media with css3 in ie9 or above can achieve the effect mentioned by the original poster. Then use js to implement the following, and add the binding of the resize event. Otherwise, the window will not be displayed when it is enlarged after hiding. The complete reference code is as follows:
<!doctype html><html><head> <meta charset="UTF-8"> <title></title> <style type="text/css"> @media screen and (max-width:800px) { #div{ color:#f00;} } </style> <!--[if lt IE 9]> <script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script> <script src="hide.js"></script> <![endif]--></head><body><div id="div">this test div</div><script type="text/javascript"> function hideDiv(){ var browserWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var div = document.getElementById("div"); if(browserWidth < 800){ div.style.display = "none"; } else { div.style.display = "block"; } } var timer = null; window.onresize = function(){ timer && clearTimeout(timer); setTimeout(function(){ hideDiv(); }, 200); } hideDiv();</script></body></html>