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

时间:2016-08-31 12:14:24

标签: javascript html

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.

2 个答案:

答案 0 :(得分:1)

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";
}}

答案 1 :(得分:1)

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>