How much of an element is visible in viewport

前端 未结 5 1603
天命终不由人
天命终不由人 2020-12-29 09:24

There\'s a div (brown rectangle) on the page. The page is higher than the viewport (orange rectangle) so it can be scrolled, which means that the div

5条回答
  •  伪装坚强ぢ
    2020-12-29 10:09

    See one more example in fiddle: https://jsfiddle.net/1hfxom6h/3/

    /*jslint browser: true*/
    /*global jQuery, window, document*/
    (function ($) {
        'use strict';
        var results = {};
    
        function display() {
            var resultString = '';
    
            $.each(results, function (key) {
                resultString += '(' + key + ': ' + Math.round(results[key]) + '%)';
            });
    
            $('p').text(resultString);
        }
    
        function calculateVisibilityForDiv(div$) {
            var windowHeight = $(window).height(),
                docScroll = $(document).scrollTop(),
                divPosition = div$.offset().top,
                divHeight = div$.height(),
                hiddenBefore = docScroll - divPosition,
                hiddenAfter = (divPosition + divHeight) - (docScroll + windowHeight);
    
            if ((docScroll > divPosition + divHeight) || (divPosition > docScroll + windowHeight)) {
                return 0;
            } else {
                var result = 100;
    
                if (hiddenBefore > 0) {
                    result -= (hiddenBefore * 100) / divHeight;
                }
    
                if (hiddenAfter > 0) {
                    result -= (hiddenAfter * 100) / divHeight;
                }
    
                return result;
            }
        }
    
        function calculateAndDisplayForAllDivs() {
            $('div').each(function () {
                var div$ = $(this);
                results[div$.attr('id')] = calculateVisibilityForDiv(div$);
            });
    
            display();
        }
    
        $(document).scroll(function () {
            calculateAndDisplayForAllDivs();
        });
    
        $(document).ready(function () {
            calculateAndDisplayForAllDivs();
        });
    }(jQuery));
    div {
        height:200px;
        width:300px;
    
        border-width:1px;
        border-style:solid;
    }
    p {
        position: fixed;
        left:320px;
        top:4px;
    }
    
    
    div1
    div2
    div3
    div4

提交回复
热议问题