当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - I want to open a new html when the screen size is below "width 700" automatically

问题描述:

I never used JavaScript before and i need some help.

I used the script below

<script type="text/javascript">

if (screen.width <= 700) {

window.location = "mobile.html";

}

</script>

but it does not work.

网友答案:

Your code runs once the page is loaded, if the window is resized the code doesn't recognise that fact. Use eventListeners:

window.onload=a;
window.onresize=a;
function a(){
  if(window.innerWidth<700){
  window.loaction="mobile.html";
}}
网友答案:

Use this function in JS, and call it in HTML on resize as given below:

HTML:

<body onresize="openHtml()" onload="openHtml()">   

--"onresize" attribute calls the function when the window is resized.

--"onload" attribute calls the function when the window is loaded for the first time.

JS:

<script>
     function openHtml()
     {
         if(window.innerWidth <= 700) {
             window.location.href = "mobile.html";
         }
     }
</script>
分享给朋友:
您可能感兴趣的文章:
随机阅读: