上下文
我正在构建一个无限水平的图像滚动:
<div class="infinite-thumbs">
<img src="1.jpg" class="thumb thumb-one">
<img src="2.jpg" class="thumb thumb-two">
<img src="3.jpg" class="thumb thumb-three">
...
<img src="10.jpg" class="thumb thumb-ten">
</div>
<style lang="stylus">
.infinite-thumbs
position absolute
width 100%
height 180px
bottom 40px
white-space nowrap
overflow auto
overflow-y hidden
.thumb
position relative
display inline-block
width 200px
height 180px
</style>
在此处了解有关 Stylus 的更多信息:stylus-lang.com
然后我有一些jQuery/JS
来处理图像在屏幕外时的克隆和附加:
function scrollUpdate() {
$('.thumb').each(function() {
var bounding = $(this)[0].getBoundingClientRect();
if (bounding.right < 0) {
var $el = $(this);
$el.clone(true).appendTo('.infinite-thumbs');
$el.remove();
}
});
}
$('.infinite-thumbs').on('scroll', function () {
window.requestAnimationFrame(scrollUpdate);
});
所以scrollUpdate()
循环遍历每个.thumb
元素并检查它是否在屏幕上可见。如果不是 ( bounding.right < 0
),那么它会被克隆并附加到.infinite-thumbs
元素的末尾。
问题
我遇到的问题是,一旦其中一个.thumb
元素返回负值,bounding.right
所有.thumb
元素都会返回完全相同的一组值bounding
。
所以当一切都可见时,我在控制台中得到了这个:
.thumb-one: { top : 0, right : 200, ... }
.thumb-two: { top : 0, right : 400, ... }
.thumb-three: { top : 0, right : 600, ... }
...
.thumb-ten: { top : 0, right : 2000, ... }
但是一旦第一个子元素 ( .thumb-one
) 获得负值bounding.right
,我就会在控制台中得到这个:
.thumb-one: { top : 0, right : -1, ... }
.thumb-two: { top : 0, right : -1, ... }
.thumb-three: { top : 0, right : -1, ... }
...
.thumb-ten: { top : 0, right : -1, ... }
是什么赋予了?为什么它们会bounding
仅仅因为其中一个不在屏幕上而返回具有完全相同值的对象?
有人知道这里发生了什么吗?
笔记:
两者
$.fn.offset()
的$.fn.position()
行为方式与getBoundingClientRect()
;相同 它们返回相同的一组值,每.thumb
一次.thumb-one
在其结果中都有一个负值。