如何刷新window宽度480px到768px之间的页面?

How to refresh the page between window widths 480px to 768px?

我目前使用的代码:

// Resize when less than 768
$(document).ready(function(){
$(window).on('resize',function(){
    if ($(window).width() < 768) {   
      location.reload();  // refresh page 
    }
    else {  
      // Width greater than 768px for PC  
    }
}); 
});

但是当浏览器调整到小于 768px 时,这会不断地重新加载页面。是否有可能有一个代码只在浏览器说 480px 和 768px 之间调整大小时重新加载页面?谢谢!

您可以在页面首次加载时(在 ready() 处理程序中)设置一个变量来检查 window 的初始大小。然后只在必要时使用调整大小事件。

$(document).ready(function(){
    var initialSize = $(window).width();

    //don't resize on small sizes
    if (initialSize < 768) { return; }

    //otherwise continue
    $(window).on('resize',function(){
        if ($(window).width() < 768 && ) {   
          location.reload();  // refresh page 
        }
        else {  
           // Width greater than 768px for PC  
        }
    }); 
});

当然可以:

// Resize when less than 768
$(document).ready(function(){
$(window).on('resize',function(){
    if (($(window).width() > 480) && ($(window).width() < 768)) {   
      location.reload();  // refresh page 
    }
    else {  
      // Width greater than 768px for PC 
      // Or width is smaller than 480 for mobile
    }
}); 
});

当我看到被接受的答案时,我正试图找到关于这个问题的解决方案..

朋友请注意言辞:

But this reloads the page constantly when the browser is resized less than 768px.

关键词constantly是误导,让别人以为是页面不断刷新的问题,而不是条件限制

无论如何,对于那些认为问题在于不断更新的可怜人,这是我的一个 working fiddle 拙劣的解决方案:

$(document).ready(function(){
    //Set flag refresh to true
    var refresh = true;
    //If the window width is between wanted limit set flag to false. This is needed for the resize*.
    if (($(window).width() > 480) && ($(window).width() < 768)) {
      refresh = false;
    }
    $(window).resize( function(){
    /* When resize hits limits check if flag is true, then refresh.
    Flag is set to false from above*, after refresh.
    Time is needed for the page to load and set the flag to false.
    Otherwise flag is not updated and constant refresh keeps happening while resizing. */
    if (($(window).width() > 480) && ($(window).width() < 768) ) {
      if (refresh == true) location.reload();
    } else {
        refresh = true;
    }
  });
});