检测特定类名的第一个可见元素

Avatar of Chris Coyier
Chris Coyier

为浏览器窗口中可见的第一个具有“activity”类的元素添加“first”类。

$(window).scroll(function(){
	var scrollTop = $(window).scrollTop();
	var windowHeight = $(window).height();		
	var first = false;
	$(".activity").each( function() {
		var offset = $(this).offset();
		if (scrollTop <= offset.top && ($(this).height() + offset.top) < (scrollTop + windowHeight) && first == false) {
			$(this).addClass("first");
			first=true;
		} else {
			$(this).removeClass("first");
			first=false;
		}
	});
});