问题
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