我正在用我认为的模块模式编写 JavaScript(我对编程还很陌生,所以如果我使用了不正确的术语,请原谅我)。
下面的脚本旨在在文档加载时测量三件事:
- 页面滚动的距离。
#eventSideBar
相对于文档顶部的 y 偏移量,- 文档的整体高度。
(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());
});
};
然后我总是能得到正确的滚动位置值。这得到了正确的结果,但看起来有点hackish。
有没有一种“正确”的方法来获取我想要的数据,而无需链接 document
方法,就像我的方法中发生的那样?
最佳答案
听起来你需要的是:
$(document).scroll(function() { exocet.init(); });
将其放入准备好的回调中。当用户滚动时必须记录结果。必须按刷新没有多大意义。
关于javascript - 如何使用模块模式检索文档数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24089144/