2

我打算 为图形和图表使用一个名为charts.js的jQuery 插件。然而,在更大的页面上,这些图表的动画甚至在用户看到它们之前就已经完成了。

我的问题是,只有当特定 div/section 的内容在视口内可见时,我们如何才能淡入它,正如 chart.js 网站上所描述的那样。当我们向下滚动时,内容会依次淡入,因此即使是图表的动画也不会错过。如何在 jQuery 的帮助下实现这一目标?

4

3 回答 3

2

看看这个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).
            }            
        });     
    });    
});
于 2013-10-22T12:46:28.403 回答
0

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

<script type="text/javascript">
$(document).ready(function() {
    $(document).on('scroll', function() {
        //Get Div 1's Top and Left offsets from the Document.
        var divTop = $('#div1').offset().top;
        var divLeft = $('#div1').offset().left;
        //Get the current window height and width.
        var winHeight = $(window).height();
        var winWidth = $(window).width();

        if (divPos <= winHeight && divLeft <= winWidth) {
            //Div is visible in window

            //Fade in Chart
        }
    });
});
</script>
于 2013-10-22T12:48:27.380 回答
0

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

我建议尝试他的另一个插件,延迟加载

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

于 2013-10-22T12:41:37.757 回答