jQuery 调整大小并在文档上准备好组合

jQuery resize and on document ready combination

我有这个 JS 函数来删除依赖于屏幕尺寸的 class。有用 仅当您调整屏幕大小时(我认为这是预期的行为),但是,我也需要让它在加载时工作。

require(['jquery'], function(){
    jQuery(window).resize(function() {
        var innerWidth = window.innerWidth;
        if (innerWidth < 800) {
            jQuery("#logo-container").removeClass('pull-left');
        } else if (innerWidth > 800) {
            jQuery("#logo-container").addClass('pull-left');
        }
    });
});

我用 document.ready 包装了函数,并在调整大小事件之前添加了相同的内容。现在有这样的东西:

require(['jquery'], function(){
    jQuery(document).ready(function() {
        var innerWidth = window.innerWidth;
        if (innerWidth < 800) {
            jQuery("#logo-container").removeClass('pull-left');
        } else if (innerWidth > 800) {
            jQuery("#logo-container").addClass('pull-left');
        }
        jQuery(window).resize(function() {
            var innerWidth = window.innerWidth;
            if (innerWidth < 800) {
                jQuery("#logo-container").removeClass('pull-left');
            } else if (innerWidth > 800) {
                jQuery("#logo-container").addClass('pull-left');
            }
        });
    });
});

现在,我的函数的结果是我想要的,但是,我觉得我在重复我的代码。

这是正确的做法吗?有没有更好的替代方法?

如有任何建议,我们将不胜感激。

请记住,如果您需要复制并粘贴完全相同的代码块,最好将其重构为函数调用:

require(['jquery'], function(){
    jQuery(document).ready(function() {
        jQuery(window).resize(function() {
            toggleClass();
        });
        toggleClass();
    });

    function toggleClass() {
        var innerWidth = window.innerWidth;
        if (innerWidth < 800) {
            jQuery("#logo-container").removeClass('pull-left');
        } else if (innerWidth > 800) {
            jQuery("#logo-container").addClass('pull-left');
        }
    }
});

避免重复代码。

创建一个函数并在文档就绪函数和 window 调整大小函数上调用它...

In the below code, all the code goes to OnScreenResized() function.

require(['jquery'], function() {
      jQuery(document).ready(function() {
        OnScreenResized();

      });

      jQuery(window).resize(function() {
        OnScreenResized();
      });

      function OnScreenResized() {
        var innerWidth = window.innerWidth;

        if (innerWidth < 800) {
          jQuery("#logo-container").removeClass('pull-left');
        } else if (innerWidth > 800) {
          jQuery("#logo-container").addClass('pull-left');
        }
      }
    });