Get the element which is the most visible on the screen

后端 未结 4 691
我寻月下人不归
我寻月下人不归 2020-12-16 03:47

I would like to get the one element which is the most visible on the screen (takes up the most space). I have added an example picture below to understand my question a bit

4条回答
  •  执笔经年
    2020-12-16 04:09

    Yes, this question is too broad. But I was interested on solving it. Here is crude example on how to accomplish it.

    I tried to explain what's going on with comments. It surely can be done better, but I hope it helps.

    // init on page ready
    $(function() {
        // check on each scroll event
        $(window).scroll(function(){
            // elements to be tested
            var _elements = $('.ele');
    
            // get most visible element (result)
            var ele = findMostVisible(_elements);
        });
    });
    
    
    function findMostVisible(_elements) {
    
        // find window top and bottom position.
        var wtop = $(window).scrollTop();
        var wbottom = wtop + $(window).height();
    
    
        var max = 0; // use to store value for testing
        var maxEle = false; // use to store most visible element
    
        // find percentage visible of each element
        _elements.each(function(){
    
            // get top and bottom position of the current element
            var top = $(this).offset().top;
            var bottom = top + $(this).height();
    
            // get percentage of the current element
            var cur = eleVisible(top, bottom, wtop, wbottom);
    
            // if current element is more visible than previous, change maxEle and test value, max 
            if(cur > max) {
                max = cur;
                maxEle = $(this);
            }
        });
    
        return maxEle;
    }
    
    // find visible percentage
    function eleVisible(top, bottom, wtop, wbottom) {
    
        var wheight = wbottom - wtop;
    
        // both bottom and top is vissible, so 100%
        if(top > wtop && top < wbottom && bottom > wtop && bottom < wbottom)
        {
            return 100;
        }
    
        // only top is visible
        if(top > wtop && top < wbottom)
        {
            return  100 + (wtop - top) / wheight * 100;
        }
    
        // only bottom is visible
        if(bottom > wtop && bottom < wbottom)
        {
            return  100 + (bottom - wbottom) / wheight * 100;
        }
    
        // element is not visible
        return 0;
    }
    

    Working example - https://jsfiddle.net/exabyssus/6o30sL24/

提交回复
热议问题