HTML how to tell which elements are visible?

前端 未结 2 1005
遥遥无期
遥遥无期 2020-12-18 03:23

I have seen several solutions which determine when an element is visible in the viewport whilst scrolling the page, but I haven\'t seen any which do this for elements that a

2条回答
  •  庸人自扰
    2020-12-18 04:04

    include jQuery library on page first.

    function getObjDims(obj){
        if (!obj) return false;
        var off = $(obj).offset();
        var t = {
            top:off.top,
            left:off.left,
            width:$(obj).width(),
            height:$(obj).height()
        };
        return {x1:t.left, y1:t.top, x2:t.left+t.width,y2:t.top+t.height}
    };
    function testInside(pic,box){
        var d=getObjDims(pic);
        return (box.x1<=d.x1 && box.y1<=d.y1 && box.x2>=d.x2 && box.y2>=d.y2)?1:-1;
    };
    $(document).ready(function(){
        var inside={};
        var port=$('#scrollContainer');
        var box=getObjDims(port);
        $(window).resize(function(){
            box=getObjDims(port);
        });
        $(port).scroll(function(){      
            var str=[];
            $('.picture').each(function(i){
                var oldState = inside[this.id]!=undefined?inside[this.id]:0;            
                var newState = testInside(this,box);
                inside[this.id]=newState;
                if (oldState!=newState)
                    switch (newState){
                        case 1:str.push(this.id);break;// go IN
                        case -1: break;// go OUT
                    }
            });
            $('#picStatus').text(str.join(', '));
        });
    });
    

    Add in HTML for results output:

    Pictures in window (numbers):

    It is code based on object's coords, witch are recalculated on scroll event. There are some things to know. IE and, seems to be, Opera takes into consideration width and height of scrollbars themselves, that demands curtain code tuning. I just have suggested solution direction and did not spent much time for debugging this.

    And yet, maybe will be useful following (from jquery api about offset):

    Note: jQuery does not support getting the offset coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.

提交回复
热议问题