如何仅在视口中显示数据

How to show data only when in viewport

本文关键字:显示 数据 视口 何仅      更新时间:2023-09-26

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

我的问题是,只有当特定div/部分的内容在视口内可见时,我们如何淡入特定div/部分的内容,如图表.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 的视口选择器插件适用于浏览器窗口视口,而不是 html 元素。换句话说,如果你有一些像 #container{width:350px;height:150px;overflow:auto;}这样的css,它在滚动时将不起作用。

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

下面是一个示例:http://jsbin.com/efazos/1/edit

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

<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>