【问题标题】:How to reload the page only when window width changes from desktop (>1024px) to mobile (<1025px) navigation?仅当窗口宽度从桌面(> 1024px)更改为移动(<1025px)导航时如何重新加载页面?
【发布时间】:2015-02-15 14:05:25
【问题描述】:

我有一个仅在 1025 像素以下运行的移动导航。 我的问题是,当桌面浏览器从超过 1024 调整大小(或在更大的平板电脑上发生方向变化)时,它不再激活脚本。我曾尝试在调整大小时重新加载,但这并不理想,因为它会在每次调整大小时重新加载。

这是我的代码:

<script>
    $(window).bind('resize', function(e)
    {
      if (window.RT) clearTimeout(window.RT);
      window.RT = setTimeout(function()
      {
        this.location.reload(false);
      }, 100);
    });

    if (document.documentElement.clientWidth <= 1024) {
      // Initialize mobile nav
    }
</script>

谢谢!

【问题讨论】:

  • 怀疑你想重新加载页面,这不是很用户友好。你为什么不只是调整调整大小处理程序中的导航?
  • 看看这个答案:stackoverflow.com/a/9720327/584599

标签: javascript resize reload


【解决方案1】:

在每个分辨率中添加类并请求它们。

$( window ).resize(function() {
if(($(window).width()>1024 && $(".navigation").hasClass("mobile")) || ($(window).width()<1025 && $(".navigation").hasClass("desktop")))
this.location.reload();
}

但您应该考虑不要重新加载,而是通过 css 媒体查询隐藏/显示导航。重新加载是用户体验的痛苦:-)

更好的解决方案:

在你的 CSS 中:

.desktop {
    display: block;
}
.mobile {
    display: none;
}
@media only screen and (max-width: 1025px) {
.desktop {
        display: none;
    }
    .mobile {
        display: block;
    }
}

在您的 html 中:

<div class="navigation desktop">your desktop navigation</div>
<div class="navigation mobile">your mobile navigation</div>

不需要 js。

【讨论】:

  • 导航实际上只有一个类(.navigation),我对桌面和移动设备的媒体查询的样式不同。只有移动导航应该用js激活。如何添加不同的类?
  • 这样吗? &lt;div class="navigation mobile"&gt;some text&lt;/div&gt;
猜你喜欢
  • 1970-01-01
  • 2014-06-26
  • 1970-01-01
  • 1970-01-01
  • 2013-10-04
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 2012-11-20
相关资源
最近更新 更多