如何仅在视口中显示数据

我打算使用一个名为charts.js的jQuery插件来绘制图形和图表。 但是,在较大的页面上,即使在用户看到之前,这些图形的动画也会完成。

我的问题是,我们如何淡化特定div / section的内容,只有当它在视口内可见时才会在charts.js网站上精确描述。 当我们向下滚动时,内容按顺序逐渐消失,因此甚至不会错过图表的动画。 如何在jQuery的帮助下实现这一目标?

看看这个 jsFiddle。 当作者变得可见时,作者会在框中淡出。 您可能需要调用chart.js来创建图形,因为它们变得可见,而不是将它们淡入(即如果您想要花哨的图形动画,而不仅仅是淡入淡出:-))我已经调整了小提琴并包括在下面:

 $(document).ready(function() { /* Every time the window is scrolled ... */ $(window).scroll( function(){ /* Check the location of each desired element */ $('.graph').each( function(i){ var bottom_of_object = $(this).position().top + $(this).outerHeight(); var bottom_of_window = $(window).scrollTop() + $(window).height(); /* If the object is completely visible in the window, fade it it */ if( bottom_of_window > bottom_of_object ){ //Code to initialize the graph here. //This initialization should probably //be deferred, to ensure performance, //and the graphs should be marked as //initialized so we dont't init them //multiple times (possibly by changing //their class so .each ignores them). } }); }); }); 

Mika的Viewport Selectors插件适用于浏览器窗口视口,而不适用于html元素。 换句话说,如果你有一些像#container {width:350px; height:150px; overflow:auto;}这样的CSS,它在滚动时将无效。

我建议尝试他的其他插件,Lazy Load

这是一个例子: http : //jsbin.com/efazos/1/edit

以下代码将使您能够确定元素是否在文档滚动的窗口内。 从那里你可以启用你的图表并做你喜欢的任何动画: