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

匿名 (未验证) 提交于 2019-12-03 01:18:02

问题:

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 solutions so far but they only seem to work for body... not a scrollable div.

I am happy to use a plugin if you know one exists. Something like this...

if ($('.journal-slider .each-slide img').inViewport() ) {     $(this).addClass('in-view'); } else {    $('.journal-slider .each-slide img').removeClass('in-view'); }

Thanks, R

回答1:

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!