我遇到以下代码的一些奇怪行为。
function linkFunc(scope, element, attribute) {
var page = angular.element($window);
page.bind('scroll', function() {
var windowHeight = "innerHeight" in window ? window.innerHeight : document.documentElement.offsetHeight;
var body = document.body, html = document.documentElement;
var docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
var windowBottom = windowHeight + window.pageYOffset;
if (windowBottom >= docHeight) {
scope.$apply(attribute.myDirective);
}
});
}
上面是一段代码,用于检测是否到达页面底部,如果到达底部,它将调用绑定(bind)到 myDirective
的任何函数。
主要问题是大多数时候延迟加载有效,并且myDirective
被成功调用。然而,有时延迟加载不起作用,我无法重现错误。
我尝试了不同的屏幕尺寸、不同的浏览器,但似乎这个错误只是随机发生的。
也许有人以前遇到过这种情况,可以给我指明方向吗?
编辑:
更多信息
经过一些试验,我能够重现该错误。
基本上,当浏览器的缩放比例为< 100 %
时, window.pageY
返回一个稍微不准确的十进制值,这会导致 windowBottom
由 0.1
关闭至 0.9
例如。
console.log(windowBottom); // 1646.7747712336175
console.log(docHeight); // 1647
有人知道为什么会这样吗?
编辑 2:
上述行为也是不确定的,但小数部分为真。
最佳答案
0.1 + 0.2 !== 0.3
This one is an oddity not just in JavaScript; it’s actually a prevailing problem in computer science, and it affects many languages. The output of this is 0.30000000000000004.
This has to do with an issue called machine precision. When JavaScript tries to execute the line above, it converts the values to their binary equivalents. This is where the problem starts. 0.1 is not really 0.1 but rather its binary equivalent, which is a near-ish (but not identical) value. In essence, as soon as you write the values, they are doomed to lose their precision. You might have just wanted two simple decimals, but what you get, as Chris Pine notes, is binary floating-point arithmetic. Sort of like wanting your text translated into Russian but getting Belorussian. Similar, but not the same.
您可以阅读更多here .在不深入浏览器源代码的情况下,我猜你的问题源于此。
关于javascript - 延迟加载有时在 Angular 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38643607/