javascript - jQuery 调整大小和文档就绪组合

标签 javascript jquery resize

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

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');
            }
        });
    });
});

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

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

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

最佳答案

避免重复代码。

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

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');
        }
      }
    });

关于javascript - jQuery 调整大小和文档就绪组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51873259/

相关文章:

javascript - 无法访问脚本中 ColdFusion 标记中的 JavaScript 变量

JAVA 如何在运行时调整 JFrame 的大小?

angular - 如何在 ionic2 中调整项目分隔符的大小

JavaScript 正则表达式 - 数字之间的连字符

javascript - Wordpress Divi 主题 - anchor 链接打开选项卡切换

javascript - 不使用 key 的简单JavaScript加密和解密

javascript - 如何打开带有数据url图像的新页面?

javascript - Meteor JS 数据库工作流程

javascript - 漂亮的格式化代码不会换行

html - 为什么我的div在调整大小时停在左边