2017-08-05 76 views
1

上下文getBoundingClientRect()的所有儿童返回相同的值,如果第一个孩子有任何负值

我建立图像的无限水平滚动:

<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-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的结果为负值。

回答

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(); 
    }); 
} 
+0

通过禁用'$ .fn.clone()'和'$ .fn.remove()'来快速测试,表明你正在做某事!我会追逐这个... – AJB

+1

我已经添加了一些代码(未经测试,但我认为你可以使用它来达到你的目标) –

+0

工程就像一个魅力!感谢阿尔贝托,让我从那里走出;) – AJB

相关问题