如何使用模块模式检索文档数据

How do I retrieve document data, using the module pattern?

本文关键字:文档 数据 检索 模式 何使用 模块      更新时间:2023-09-26

我正在编写我认为是模块模式的javascript(我对编程仍然很陌生,所以如果我使用了不正确的术语,请原谅我)。

下面的脚本用于在文档加载时测量三件事:

  1. 页面滚动距离。
  2. #eventSideBar相对于文档顶部的y轴偏移量
  3. 文件的整体高度

(function (exocet, $, undefined) {
    var scrollDistance = function() {
        return $('body').scrollTop()
    }
    var sideBarOffset = function() {
        return $('#eventSideBar').offset().top;
    }
    var allHeight = function() {
        return $('body').height();
    }
    exocet.init = function() {
        console.log('Scroll distance: ' + scrollDistance() +
                    ' Sidebar offset: ' + sideBarOffset() +
                    ' Total height: ' + allHeight()
        );
    };
}(window.exocet = window.exocet || {}, jQuery));
$(document).ready(function() {
    exocet.init();
});

当将这些记录到控制台时,始终正确返回的唯一值(在Chrome中测试)是sideBarOffset。而scrollDistance总是返回0,allHeight变化+/-约1000px。

如果我将exocet.init更改为:

exocet.init = function() {
    console.log('Scroll distance: ' + scrollDistance() +
                ' Sidebar offset: ' + sideBarOffset() +
                ' Total height: ' + allHeight()
    );
    $(document).scroll(function(){
        console.log('Scroll is now: ' + scrollDistance());
    });
};

我总是得到正确的滚动位置值。这样可以得到正确的结果,但是看起来有点俗气。

是否有一种"适当"的方式来获得我在没有链接document方法之后的数据,就像我的方法中发生的那样?

听起来你需要的是:

$(document).scroll(function() { exocet.init(); });

把它放到ready回调中。用户滚动时必须记录结果。按刷新没有多大意义

@beautifulcoder的示例将在每次文档滚动时工作。如果您只想要页面加载时的滚动位置(即,如果先前在页面上保存了滚动位置),那么您可以将exocet.init()函数放在load事件处理程序中,并使用短超时来捕获初始滚动位置:

    $(window).on('load', function() {
        setTimeout(function() {
            exocet.init();
        }, 200);
    });

如果两者都需要,那么也可以使用scroll事件处理程序。

修改后的JSBin示例。