【问题标题】:How can I push down page content after header?如何在标题后下推页面内容?
【发布时间】:2023-02-11 07:29:52
【问题描述】:

我有一个 wordpress 网站。 该代码有时有效。我很困惑为什么有时它会正确地添加 mastHeight 的边距而其他时候它会增加额外的边距。我怀疑它必须对脚本运行时未完全加载的页面执行某些操作。有人可以指导我正确的方向吗?

这是我在网站上运行的代码:

<script>    
jQuery(document).ready(function($) {
     // When the window resizes
    $(window).on('resize', function () {
         // Get the height + padding + border of `#masthead`
        var mastHeight = $("#global-header-section").innerHeight();
        // Add the height to `.site-content`
        $("#et-main-area").css('margin-top', mastHeight);
    });
     // Trigger the function on document load.
    $(window).trigger('resize');
});
</script>

【问题讨论】:

    标签: jquery wordpress


    【解决方案1】:

    您拥有的脚本可能无法按预期工作,因为脚本运行时页面可能未完全加载。为确保脚本仅在页面完全加载时运行,您可以通过以下方式包装整个脚本:

    jQuery(window).on("load", function() {
      // Your script code here
    });
    

    这将确保脚本仅在加载页面上的所有元素(包括图像和其他资源)时运行。另一个问题可能是脚本在同一页面上运行了多次,这可能会导致 margin-top 值计算错误。为避免这种情况,您可以将脚本包装在立即调用的函数表达式 (IIFE) 中以创建闭包,如下所示:

    (function($) {
      $(document).ready(function() {
        // When the window resizes
        $(window).on('resize', function() {
          // Get the height + padding + border of `#masthead`
          var mastHeight = $("#global-header-section").innerHeight();
          // Add the height to `.site-content`
          $("#et-main-area").css('margin-top', mastHeight);
        });
        // Trigger the function on document load.
        $(window).trigger('resize');
      });
    })(jQuery);
    

    这将确保脚本只正确运行一次,并且闭包内定义的任何变量都不能从闭包外访问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-26
      • 2015-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多