【发布时间】:2018-03-26 09:27:23
【问题描述】:
我目前有一个脚本,我在其中跟踪元素的 .offset() 位置。当这个元素到达窗口的顶部、左侧、底部或右侧边缘时,我需要调用一个函数,该函数应该只调用一次,然后在下一次碰到窗口边缘时再次调用。
现在我有这个:
var exceededBounds = false
function checkPosition(element) {
var pos = element.offset();
var maxBoundsX = $(window).width();
var maxBoundsY = $(window).height();
var minBoundsX = 0
var minBoundsY = 0
// if the element hits one of the edges of the window
if (pos.left >= maxBoundsX || pos.top >= maxBoundsY || pos.left <= minBoundsX || pos.top <= minBoundsY) {
if (!exceededBounds) {
exceededBounds = true
}
else {
exceededBounds = false
}
}
else {
exceededBounds = exceededBounds;
}
}
function something() {
// do something here, which only happens once
}
function init() {
checkPosition(element);
if (exceededBounds) {
something()
}
requestAnimationFrame(init);
}
requestAnimationFrame(init);
问题是,something() 函数被多次调用,我相信是由于 requestanimationframe() 的帧速率?我需要使用 requestanimationframe,但是我只想在变量超出范围发生变化时调用 something() 函数。我想过在这里尝试实现某种观察的东西,但是对于我真正需要的东西来说感觉太复杂了。
谢谢
【问题讨论】:
-
你试过把
exceededBounds = false;放在if (exceededBounds)里面吗?这样,您将继续使用checkPosition(element);检查元素的位置,但something()只会在exceededBounds在checkPosition(element)内再次设置为true时运行 -
方法错误。不要使用
requestAnimationFrame()。请改用MutationObserver`。
标签: javascript jquery html observable requestanimationframe