Detect when elements within a scrollable div are out of view

前端 未结 8 1811
我寻月下人不归
我寻月下人不归 2020-12-24 13:15

I need to find a good solution to the following problem. I see a lot of people asking about tracking if an element is in or outside of view Port for the page or browser wind

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-24 13:37

    I made a jquery plugin with the last answer:

    (function($) {
        $.fn.reallyVisible = function(opt) {
    
            var options = $.extend({
                cssChanges:[
                    { name : 'visibility', states : ['hidden','visible'] }
                ],
                childrenClass:'mentioners2',
                partialview : true
            }, opt);
    
            var container = $(this);
            var contHeight;
            var contTop;
            var contBottom;
            var _this = this;
            var _children;
    
            this.checkInView = function(elem,partial){
    
                var elemTop = $(elem).offset().top - container.offset().top;
                var elemBottom = elemTop + $(elem).height();
    
                var isTotal = (elemTop >= 0 && elemBottom <=contHeight);
                var isPart = ((elemTop < 0 && elemBottom > 0 ) || (elemTop > 0 && elemTop <= container.height())) && partial ;
    
                return  isTotal  || isPart ;
            }
    
            this.bind('restoreProperties',function(){
                $.each(_children,function(i,elem){
                    $.each(options.cssChanges,function(i,_property){
                        $(elem).css(_property.name,_property.states[1]);        
                    });
                });
                _children = null;
            });
    
            return this.each(function(){
                contHeight = container.height();
                contTop = container.scrollTop();
                contBottom = contTop + contHeight ;
    
                _children = container.children("."+options.childrenClass);
    
                $.each(_children,function(i,elem){
                    var res = _this.checkInView(elem,options.partialview);
                    if(  !res ){
                        $.each(options.cssChanges,function(i,_property){
                            $(elem).css(_property.name,_property.states[0]);        
                        });
                    }
                });
    
            }); 
        }
    
    })(jQuery);
    

提交回复
热议问题