How can I execute a function on an element as soon as it comes into开发者_开发百科 view of the window when I scroll down?
I might as well post it here as an answer:
function elementInView($elem, vps, vpe) {
var elempos = $elem.position();
var pagestart = elempos.top + vps;
var pageend = elempos.top + vps + $elem.height();
var offset = $elem.height() - Math.max(0,vps-pagestart) - Math.max(0,pageend-vpe);
return (vpe > 0 && offset > -200);
}
$('#container').bind('scroll', function() {
var $container = $(this);
var vps = $container.scrollTop();
var vpe = vps + $container.height();
$('li', '#container').each(function() {
var $this = $(this);
if (elementInView($this,vps,vpe)) {
// $this is now in view
}
});
});
I realize this has some performance issues, and can be optimized, but it should be a start.
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}
via https://stackoverflow.com/questions/487073/jquery-check-if-element-is-visible-after-scroling
精彩评论