【问题标题】:jQuery resize and on document ready combinationjQuery 调整大小和文档就绪组合
【发布时间】:2018-08-16 08:58:15
【问题描述】:

我有这个 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 包装了函数,并在 resize 事件之前添加了相同的内容。现在有这样的东西:

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

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

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

我们将不胜感激。

【问题讨论】:

  • 您可以通过创建新函数并在每个条件下调用它来调整大小,以防止再次重写所有语句
  • 添加一个函数并调用它..
  • 我明白了!现在得到我的答案!感谢您的帮助。

标签: javascript jquery resize


【解决方案1】:

避免重复代码。

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

在下面的代码中,所有代码都转到OnScreenResized()函数。

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

【讨论】:

  • 啊太棒了!感谢您的帮助和建议!
【解决方案2】:

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

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

【讨论】:

  • 太棒了!感谢您的帮助和建议。
猜你喜欢
  • 2012-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-18
相关资源
最近更新 更多