我以为$(window).scrollTop会告诉我我滚动了多少,但是.
如果我稍微滚动一下,我会得到:
$(window).scrollTop(): 0
$('#react-root')[0].scrollTop: 0
$('#react-root')[0].getBoundingClientRect().top: -450 // that seems to be correct#react-root直接附着在身体上,包含所有的东西。事情是怎么发生的?
====编辑===
好的,我碰巧有一个不寻常的溢出设置:
html {
overflow: hidden;
height: 100%;
}
body {
height: 100%;
overflow: scroll;
}我为了避免滚动(https://stackoverflow.com/a/17899813/2054629)而做的事,却忘记了这一点。
下面是一个复制问题https://jsfiddle.net/7ugf4jm5/7/的jsfiddle,其中没有一个元素有一个正的滚动顶,而滚动确实发生。
====目标====
在jsfiddle描述的设置中,我感兴趣的是获得滚动偏移量(似乎getBoundingClientRect返回它),并能够将滚动位置重置到顶部。
发布于 2016-04-20 19:37:20
我做这个小提琴是为了给你举一个例子:https://jsfiddle.net/7ugf4jm5/
Fiddle中的内元
当滚动内部元素时:
console.log("Inner ID: " + $('#inner')[0].scrollTop);
console.log("Window: " + $(window).scrollTop());
console.log("Inner ID Bound: " + $('#inner')[0].getBoundingClientRect().top);将产出:
Inner ID: 555.5555702727522
Window: 0
Inner ID Bound: 7.986111640930176 --> Only because there is a slight padding at the top of the elementFiddle中的外元
console.log("React ID: " + $('#react-root')[0].scrollTop);
console.log("Window: " + $(window).scrollTop());
console.log("React ID Bound: " + $('#react-root')[0].getBoundingClientRect().top);产出:
React ID: 0
Window: 666.6666843273026
React ID Bound: -658.6806030273438当浏览器被滚动时,$(window).scrollTop()将工作。如果您的react-root设置为溢出滚动,则它将保持在窗口顶部,因此窗口不是正在滚动的窗口。您可以在我的小提琴中看到用红色勾画的元素。
但是,如果滚动窗口,则计算react-root和window滚动顶。它们略有不同,但这可能是因为浏览器中调用每一个的时间略有不同(一个本质上是在other..just之后调用的,时间差很小)。
在本例中,scrollTop和getBoundingClientRect()是彼此之间的符号逆。
https://stackoverflow.com/questions/36753065
复制相似问题