简体   繁体   中英

How to know which is the top element showing in div

The question in this link answers how to know if an element is visible after scrolling. ( Check if element is visible after scrolling ). I have a slightly different situation: I have a scrolling div , with many elements within it identified by id. At any given time, how can I know which one is the top element showing in the div ? I am using angular.js, so what I have in mind is to have a variable in my scope that is constantly updated with the top element that appears in the scrolling div .

You can create a directive that hooks to the element's scoll event and then detects the closest to its top, by iterating over all children and comparing their offsetTop to its own offsetTop + scrollTop .

.directive('detectClosestToTop', function ($timeout) {
    function findClosestToTop(root) {
        var closestElem;
        var closestTop = root.scrollHeight;
        var minTop     = root.offsetTop + root.scrollTop;

        [].forEach.call(root.children, function (child) {
            var childTop = child.offsetTop;
            if ((childTop >= minTop) && (childTop < closestTop)) {
                closestElem = child;
                closestTop  = childTop;
            }
        });

        return closestElem;
    }

    return {
        restrict: 'A',
        link: function (scope, elem) {
            // Create a the onScroll listener
            function detectClosest() {
                scope.closestToTop = findClosestToTop(elem[0]);
            }
            function onScroll() {
                scope.$apply(detectClosest);
            }

            // Register the listener and make sure we clean up,
            // when/if the element is removed
            elem.on('scroll', onScroll);
            scope.$on('$destroy', function () {
                elem.off('scroll', onScroll);
            });

            // Initialize `scope.closestToTop`,
            // after the content has been rendered
            $timeout(detectClosest);
        }
    };
});

See, also, this short demo .

It depends what elements are in your scrolling divs.. If all them are divs then everytime you scroll you just need to calculate like this:

$('.outer-div').scroll(function(){
    $('div').each(function(){
        if($('.outer-div').scrollTop() + $('.outer-div').height() > $(this).offset().top && $('.outer-div').scrollTop() < $(this).offset().top){
            console.log("shown in div")
        }
    });
});

Note: I haven't tested it yet, so maybe there is a typo.. Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM