Add class to div when in viewport

匆匆过客 提交于 2020-01-07 03:59:10

问题


I want to add a class to a menu item when a different div enters the viewport.

I have successfully replicated the alert found here: http://jsfiddle.net/blowsie/M2RzU/ However, when I try to change it from an alert to an addClass or toggleClass it breaks. This is my code:

$('#portfolio').bind('inview', function (event, visible) {
  if (visible == true) {
    // element is now visible in the viewport
    $( "#menu-item-portfolio" ).addClass( ".active-area" );
  } else {
    // element has gone out of viewport
  }
});`

I want to add .active-area to #menu-item-portfolio when #portfolio enters the viewport, then remove it when #portfolio leaves the viewport.


回答1:


I found the solution. There was a typo in the code. Instead of .addClass(".active-area") it should be .addClass("active-area")




回答2:


try this

$(document).ready(function(){
$('.myclass').bind('inview', function (event, visible) {
  if (visible == true) {
    // element is now visible in the viewport
   $("h2").removeClass('myclass');
      alert('found h2!')
  } else {
    // element has gone out of viewport
     $("h2").addClass('myclass');
  }
});
});

Demo

http://jsfiddle.net/M2RzU/24/




回答3:


You should trigger the event inview on document ready.

$('.myclass').trigger('inview');

Working Fiddle

View the changes in console in fiddle.



来源:https://stackoverflow.com/questions/21214810/add-class-to-div-when-in-viewport

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