1

上下文

我正在构建一个无限水平的图像滚动:

<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在其结果中都有一个负值。

4

1 回答 1

1

发生这种情况是因为您在检查所有拇指位置之前删除了该元素。删除第一个元素会导致下一个元素成为第一个元素,离开屏幕。这样,每个拇指都将呈现相同的“正确”位置。

解决方案 在“每个”循环之外创建一个临时数组,并使用它来保存屏幕外拇指。然后,在循环之后,以与之前相同的方式克隆、删除和附加元素。像这样的东西:

function scrollUpdate() {
    var offScreenElements = [];
    $('.thumb').each(function() {

        var bounding = $(this)[0].getBoundingClientRect();

        if (bounding.right < 0) {
            offScreenElements.push($(this));
        }
    });
    $.each(offScreenElements, function(index, element) {
        element.clone(true).appendTo('.infinite-thumbs');
        element.remove();
    });
}
于 2017-08-05T02:49:04.897 回答