I've got a side scrolling / horizontal layout site I'm building. I use a function to test whether or not an element is in the viewport on "normal" vertical layout sites in order to add classes, animations, etc. once it comes into view.
I'm trying to get the same effect for the horizontal layout, but to no avail.
Here is the regular version of the function -
$.fn.isInViewport = function() {
if ( $(this).length ) {
var elementTop = $(this).offset().top;
}
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
And here is the way I tried it for horizontal layouts, which didn't work.
$.fn.isInViewport = function() {
if ( $(this).length ) {
var elementLeft = $(this).offset().left;
}
var elementRight = elementLeft + $(this).outerWidth();
var viewportLeft = $(window).scrollLeft();
var viewportRight = viewportLeft + $(window).width();
return elementRight > viewportLeft && elementLeft < viewportRight;
};
You call the function like so
$(".element").each(function() {
if ( $(this).isInViewport() ) {
$(this).addClass("animate-element");
}
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…