代码之家  ›  专栏  ›  技术社区  ›  AJB

如果第一个子元素有任何负值,则getBoundingClientRect()为所有子元素返回相同的值

  •  1
  • AJB  · 技术社区  · 9 年前

    我正在构建一个无限的图像水平卷轴:

    <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



    问题

    拇指 元素为返回负值 bounding.right 这个 拇指 元素返回完全相同的 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 )获得负值

    .thumb-one: { top : 0, right : -1, ... }
    .thumb-two: { top : 0, right : -1, ... }
    .thumb-three: { top : 0, right : -1, ... }
    ...
    .thumb-ten: { top : 0, right : -1, ... }
    

    有什么好处?为什么他们都会返回一个 边界

    有人知道这是怎么回事吗?



    注:

    二者都 $.fn.offset() $.fn.position() 行为方式与 getBoundingClientRect() ; 它们分别返回相同的值集 一旦 .拇指一号

    1 回复  |  直到 9 年前
        1
  •  1
  •   Alberto Fecchi    9 年前

    这是因为在检查所有拇指位置之前移除了元素。删除第一个元素会导致下一个元素成为第一个,并离开屏幕。这样,每个拇指都将处于相同的“右”位置。

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

    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();
        });
    }
    
    推荐文章