Add class to element when scrolled into view (scrollable div)

后端 未结 3 1537
滥情空心
滥情空心 2020-12-11 21:01

Is there a solution for adding a class to the element in view when scrolling, and removing when out of view? This needs to work for a scrollable div. I have found a few solu

3条回答
  •  盖世英雄少女心
    2020-12-11 21:52

    The plugin you are looking for is called waypoints

    Quote from the "Get Started" :

    "Let's say you have a div with overflow:scroll, and you want a waypoint inside of this scrollable element. The context option lets you do this. Scroll the box below."

    $('#example-context').waypoint(function() {
        notify('Hit top of context');
    }, { context: '.example-scroll-div' });
    

    EDIT: Not using waypoints

    Based on what you already did, I came to this :

    function  checkInView(elem,partial)
    {
        var container = $(".scrollable");
        var contHeight = container.height();
        var contTop = container.scrollTop();
        var contBottom = contTop + contHeight ;
     
        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 ;
    }
    
    $(document).ready(function(){
    $(".scrollable").scroll(function(){
        var result="",result2="";
       $.each( $(".scrollable p"),function(i,e){
           if (checkInView($(e),false)) {
               $( this ).addClass( "red" );
           } else {
               $( this ).removeClass( "red" );
           }
            result += " " +  checkInView($(e),false);
           result2 += " " +  checkInView($(e),true);
        });
        $("#tt").text(result);
        $("#kk").text(result2);
    });
    });
    .scrollable{
        margin:10px;
        height:100px;
        overflow-y:scroll;
    }
    p
    {
        border-width:1px;
        border-color:black;
        border-style:solid;
    }
    .red {
        background-color: red;
    }
    
    full:  
    part:

    item1

    item2

    item3

    item4

    item5

    item6

    item7

    item8

提交回复
热议问题