Get the element which is the most visible on the screen

后端 未结 4 704
我寻月下人不归
我寻月下人不归 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:10

    Possible with getBoundingClientRect()

    added a jQuery plugin

    Iterate through the seleted elements and check

    • is the element in viewport?
    • whats the element's visible height?
    • is the element the most visible one?

    function getMostVisibleElement(selector) {
        var clientRect = null;
        var clientRectTop = 0;
        var maxVisibleHeight = 0;
        var visibleHeightOfElem = 0;
        var mostVisibleElement = null;
        var skipRest = false;
    
        var visibleElems = $(selector).each(function(i, element) {
            if (skipRest === false) {
                clientRect = element.getBoundingClientRect();
                clientRectTop = Math.abs(clientRect.top);
    
                if (clientRect.top >= 0) {
                    visibleHeightOfElem = window.innerHeight - clientRectTop;
                } else {
                    visibleHeightOfElem = clientRect.height - clientRectTop;
                }
    
                if (visibleHeightOfElem >= clientRect.height) {
                    mostVisibleElement = element;
                    skipRest = true;
                } else {
    
                    if (visibleHeightOfElem > maxVisibleHeight) {
                        maxVisibleHeight = visibleHeightOfElem;
                        mostVisibleElement = element;
                    }
                }
    
            }
        });
        return mostVisibleElement;
    }
    
    $(window).on('click', function() {
        var mostVisible = getMostVisibleElement('.my-container');
        $(mostVisible).addClass('highlighted');
        
        setTimeout(function() {
          $(mostVisible).removeClass('highlighted');
        }, 200);
        // alert(mostVisible.id)
    });
    .my-container {
      height: 100vh;
    }
    
    #a {
      background: #007bff;
    }
    
    #b {
      background: #28a745;
      height: 70vh;
    }
    
    #c {
      background: #ffc107;
    }
    
    #d {
      background: #17a2b8;
    }
    
    .highlighted {
      background: #dc3545 !important; 
    }
    
    
    

提交回复
热议问题