如何最有效地检查某些“断点”在浏览器重新调整大小? [英] How to most efficiently check for certain "breakpoints" upon browser re-size?

查看:87
本文介绍了如何最有效地检查某些“断点”在浏览器重新调整大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些定义了两个断点的响应式设计:

I'm playing with some responsive design that have two breakpoints defined:

Mobile > max-width 320px
Tablet portrait > max-width 767px

在桌面上我有很多动画+高级功能正在使用Javascript。在移动设备和平板电脑上,我希望简化和禁用一些JS +重建一些DOM元素。

On desktop I have a lot of animation + advanced functionality going on with Javascript. On mobile and tablet im looking to simplify and disable both some JS + "re-building" some DOM elements.

我想知道最有效的确定方法是什么某些断点(宽度方面)会是什么?我在这里考虑了很多性能。

我知道我可以通过以下方式检查窗口宽度:

I know I can simply check for the window width upon re-size with something like:

$( window ).resize(function() {
  if ($(window).width() > 320 && $(window).width() < 400) {
    //mobile
  }
  if ($(window).width() > 401 && $(window).width() < 768) {
    //tablet
  }
  if ($(window).width() > 769) {
    //desktop
  }
});

但这似乎是一个非常昂贵的操作?

But that seems like a very "expensive" operation?

对于可用于此的轻量级库的任何建议也非常受欢迎!

Any suggestions to lightweight libraries that can be used for this is also very welcome!

推荐答案

我经常遇到这个问题并没有找到完美的解决方案。但是,有一种解决方法似乎不那么耗费资源。通过在 resize()函数中使用超时并不断清除它,您可以确保只在视口停止调整大小时才运行代码。

I often ran into this problem and have not found the perfect solution. However, there is a workaround that seems less resource hungry. By using a timeout inside your resize() function and constantly clearing it, you can make sure that your code is only run, once the viewport has stopped resizing.

var resizeTimer, width;
var mobile = tablet = desktop = false;

$(window).resize(function() {
    // clear the timeout
    clearTimeout(resizeTimer);

    // execute breakpointChange() once the viewport 
    // has stopped changing in size for 400ms
    resizeTimer = setTimeout(breakpointChange(), 400);
});

function breakpointChange() {
    // use vanillajs window.innerWidth 
    // instead of jQuery $(window).width() as suggested by simon
    width = window.innerWidth;

    if (!mobile && width < 400) {
        tablet = desktop = false;
        mobile = true;
        console.log('is mobile');
    }

    if (!tablet && width > 401 && width < 768) {
        mobile = desktop = false;
        tablet = true;
        console.log('is tablet');
    }

    if (!desktop && width > 769) {
        mobile = tablet = false;
        desktop = true;
        console.log('is desktop');
    }
}
$(window).resize();

这肯定不是最好的,但它会阻止你的代码经常运行。随意添加到我的答案和/或纠正我。这是一个小提琴

This is certainly not the best one can do, but it will prevent that your code is constantly being run. Feel free to add to my answer and/or correct me. Here is a fiddle

这篇关于如何最有效地检查某些“断点”在浏览器重新调整大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆